Unsigned Int?

Hi,
I am writing a program that calculates the probability of picking a set of numbers from a larger set (ie. Lotto 649). Both of the numbers sets are user supplied and passed through a function to calculate the probability. Because they cannot be negative I used unsigned int for both the main() and function parameters.

long double calculateProbability( unsigned int numbers, unsigned int picks )
{
long double result = 1;
for( unsigned int n = numbers, p = picks; p > 0; n--, p-- )
result = result * n/p;
return result;
}

int main()
{
unsigned int numbers, picks = 0;
cout << "Probability Calculator (c) 2011 Jesse Carter";
cout << "\n---------------------------------------------";
cout << "\n\nEnter the number you are guessing from followed by how many picks you get: ";
while(cin >> numbers >> picks)
{
if( picks <= numbers )
{
cout << "\nThe odds of you picking " << picks << " number(s) from " << numbers << " is... \nOne chance in " << calculateProbability( numbers, picks ) << " of winning.\n";
cout << "\nNext 2 numbers: ";
}
else
{
cout << "The number of picks cannot be higher than the total number \nyou are guessing from.\n";
cout << "\nNext 2 numbers: ";
}
}
}

For some reason when I pass negative numbers into the program it will either default into the else statement or the program will not respond to the input at all. I wanted for the program to just drop the negative symbol and execute as if the input were positive integers. Is there an easy way to do this? I thought that is what the unsigned int datatype did.
closed account (1yR4jE8b)
When you input a negative number into an unsigned variable, you are getting integer wrap-around: -1 value assigned to an unsigned int will give you the highest positive integer value.

If you want to eliminate the minus, just use a regular int (so you don't get wrap around) then just eliminate the sign by getting the absolute value using the C function abs from the <cstdlib> header.
Last edited on
Thanks that worked great
Topic archived. No new replies allowed.