Question
Why does not this C++ code work like it should work? It is basically a lottery where the user first enters the total amount of
Why does not this C++ code work like it should work? It is basically a lottery where the user first enters the total amount of balls and then the amount of balls to be drawn. Then the program should proceed to count the probability to win:
It is also said that I should probably use something like "unsigned long int" but I do not know where to put it so here's the code:
#include
#include
using namespace std;
int read_input(string question) {
int user_input;
while (true) {
cout << question;
cin >> user_input;
if (user_input > 0) {
return user_input;
} else {
cout << "The number of balls must be a positive number." << endl;
}
}
}
int factorial(int i) {
int k = 1;
while (i > 0) {
k *= i;
i -= 1;
}
return k;
}
int calculate_probability(int n, int p) {
return int(factorial(n) / (factorial(n - p) * factorial(p)));
}
int main() {
int balls_tot = read_input("Enter the total number of lottery balls: ");
int ball_count = read_input("Enter the number of the drawn balls: ");
if (balls_tot <= 0) {
cout << "The number of balls must be a positive number." << endl;
} else if (ball_count > balls_tot) {
cout << "At most the total number of balls can be drawn." << endl;
} else {
cout << "The probability of guessing all " << ball_count << " balls correctly is 1/" << calculate_probability(balls_tot, ball_count) << endl;
}
return 0;
}
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started