// // lotto5.cpp // CSC 215 // John Rogers // // This program computes the odds of // winning the lottery, allowing the user // to repeat the calculations. // #include #include void getInput(long& numberOfBalls, long& numberChosen); long factorial(long n); long falling(long n, long k); char getAnswer(); int main() { long numberOfBalls, numberChosen, odds; char answer; do { getInput(numberOfBalls, numberChosen); 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 prompts for the number of balls in the lottery and // the number chosen. It forces the user to enter positive // values and to make the number chosen less than or equal to // the number of balls. // // It uses call-by-reference parameters to pass two values // back to the main function. // void getInput(long& numberOfBalls, long& numberChosen) { do { cout << "How many balls are in the game? Enter 1 or more: "; cin >> numberOfBalls; } while (numberOfBalls < 1); do { cout << "How many balls are chosen from that? " << endl << "This must be between 1 and " << numberOfBalls << ": " ; cin >> numberChosen; } while (numberChosen > numberOfBalls || numberChosen < 1); return; } // // 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; }