Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

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

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Oracle 12c SQL

Authors: Joan Casteel

3rd edition

1305251032, 978-1305251038

More Books

Students also viewed these Databases questions

Question

What should be the role of managers in HRD?

Answered: 1 week ago

Question

3. Provide advice on how to help a plateaued employee.

Answered: 1 week ago