// // lotto6.cpp // CSC 215 // John Rogers // // This program computes the odds of // winning the lottery, allowing the user // to repeat the calculations. // #include #include long getInteger(long low, long high, char prompt[]); long factorial(long n); long falling(long n, long k); char getAnswer(); int main() { long numberOfBalls, numberChosen, odds; char answer; do { numberOfBalls = getInteger(1, 1000, "Enter the number of balls: "); numberChosen = getInteger(1, numberOfBalls, "Enter the number chosen: "); odds = falling(numberOfBalls, numberChosen) / factorial(numberChosen); cout << "The odds of winning are " << odds << ":1." << endl; cout << "Do you wish to repeat for another game? "; answer = getAnswer(); } while (answer == 'Y'); return 0; } // // This function prompts for and returns as its value an // integer greater than or equal to the parameter low and // less than or equal to the parameter high. // long getInteger(long low, long high, char prompt[]) { long answer; do { cout << prompt; cin >> answer; } while (answer < low || answer > high); return answer; } // // This computes n! recursively. // long factorial(long n) { if (n == 0) { return 1; } else { return n * factorial(n-1); } } // // This computes n to the falling k power // recursively. In mathematical text, we write // "n to the falling k power" as n^k_ (that is, the // k is underlined). Its definition is: // // n^k_ = n*(n-1)*(n-2)*...*(n-k+1) // long falling(long n, long k) { if (k == 0) { return 1; } else { return n * falling(n-1, k-1); } } // // This waits until the user types in Y or N. // char getAnswer() { char answer; do { cin >> answer; answer = toupper(answer); } while (answer != 'Y' && answer != 'N'); return answer; }