Printf comes out negative
An answer to this question on Stack Overflow.
Question
I'm new to programming and am trying to have my program take a given number, double it, then continue to double for however many days the user input. I made this loop and it works but the final number comes out negative. I'm not sure how I can stop it from coming out negative and would appreciate any help.
int main(void)
{
int d;
int s;
float a;
do
{
printf ("Please enter the amount of days in the month: ");
d = GetInt();
} while (d > 31 || d < 28);
do
{
printf("Please enter the amount of pennies you start will start with: ");
s = GetInt();
} while( s < 0);
do
{
s = s * 2;
d = d - 1;
a = s / 100.0;
printf("%f\n", a);
} while(d > 0);
return 0;
}
Answer
The problem is here:
s=s*2;
(Though you should be sure to always initialize your variables, e.g. s=0 before the loop.)
Integers don't have a special value for when the number gets larger than the storage type, so they overflow.
Here's an example of that could happen. Imagine that we store integers as a series of 4 bits where the first bit means that a number is negative. If we then begin counting in our system, we get the following:
0000 = 0
0001 = 1
0010 = 2
0011 = 3
0100 = 4
0101 = 5
0110 = 6
0111 = 7
1000 = -0
1001 = -1
1010 = -2
So you can see that the numbers keep on growing inside the computer, but what they translate to suddenly becomes negative when the most significant bit is flipped on.
Computers use all kinds of different schemes for storing negative numbers, but Two's Complement is common. It's more clever than the system I've used to explain things here, but the essential point remains the same: when numbers get too big they become negative. In the case of an int the cross-over point is often when you hit 2^31, or 2147483648.
A workaround is to use unsigned int, which roughly doubles the largest number you can represent, or long, long long, unsigned long, or unsigned long long. Remember, this won't solve your problem, it will just give you larger numbers you can work with before a problem appears.
You can find the largest usable value using the limits.h header file; for an int it is INT_MAX.