I'm writing a program that displays the odds of winning a lottery. Unfortunately what I wrote is displaying my odds of winning as "1 in inf" rather than an expected numerical output. Is this my IDE or an issue with my code?
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <iomanip>
usingnamespace std;
// factorial function
float Factorial(int f) {
float total = 0;
for (int i = 1; i <= f; i++) {
total = total * i;
}
return total;
}
float Odds(constint nb, constint tr) {
float sum = 1.0;
int numballs = nb;
cout << "Top Range is " << tr << " number balls is " << nb << endl;
for (int i = tr - nb + 1; i <= tr; i++) {
sum = (sum * i);
}
return sum / Factorial(nb);
}
int main() {
int num_values = 0;
int range = 0;
int num_gens = 0;
float odds = 0.0;
// input collection
cout << "Enter in the number of balls or numbers you wish to pick from.\n";
while (num_values < 3 || num_values > 7) {
cout << "Number must be between 3 and 7 inclusive.\n";
cout << "> ";
cin >> num_values;
}
cout << "\nEnter in the largest number in the lottery.\n";
while (range < 45 || range > 70) {
cout << "Number must be between 45 and 70 inclusive.\n";
cout << "> ";
cin >> range;
}
cout << "\nEnter the number of tickets.\n";
while (num_gens < 1 || num_gens > 100) {
cout << "Number must be between 1 and 100 inclusive.\n";
cout << "> ";
cin >> num_gens;
}
// generate odds
cout << "\n";
odds = Odds(num_values, range);
// output
cout << "\nYou will select " << num_values << " numbers.\n";
cout << "The numbers will range from 1 to " << range << ".\n";
cout << "The odds are 1 in " << odds << ".\n";
}
You don't need a factorial function at all, so float is OK for a single ticket. (In fact, with those maximum ranges you could do it in a long long int).
You appear to have ignored the number of tickets bought.
For ONE ticket:
1 2 3 4 5 6
float Odds( int nb, int tr )
{
float result = 1;
for ( int i = 1; i <= nb; i++) result *= ( tr - i + 1.0 ) / i;
return result;
}
or you could do it with an integer type if you are careful with the order of multiplication:
1 2 3 4 5 6
unsignedlonglong Odds( int nb, int tr )
{
unsignedlonglong result = 1;
for ( int i = 1; i <= nb; i++ ) result = result * ( tr - i + 1 ) / i; // *** BE CAREFUL!
return result;
}
Later on (when you get around to multiple tickets) you may need to work with probabilities:
1 - (1-p)n
where p = 1/(odds) and could be very small, so floating-point inaccuracy would suggest the use of a double (at least for p).
iostream to just write an integer. iomanip lets you format your output a bit more. there are many, many ways to format and handle output, string stream, direct string manipulation (eg std::tostring), and the new format tools (https://en.cppreference.com/w/cpp/utility/format) to name a few.
generally I prefer a premade lookup table of things like factorial where it takes a loop to find the next value but you only can fit a small # of values in standard data types.