This is most likely because you have some locale where the decimal separator is ,
instead of .
, and since you are very likely not checking the return value of scanf()
"which is what most books do and almost every tutorial", then the variable is not being initialized and what you are printing is a consequence of the layout of your program instead of a value inputed by a user.
To verify what I say, I suggest compiling the same program without modification but with different compilation flags.
What you must do is ensure that the input is correct, try this
float GetFloat(int *ok)
{
float value = 0;
if (scanf("%f", &value) != 1)
*ok = 0;
else
*ok = 1;
return value;
}
which you would call like this
int result = 0;
float change = GetFloat(&result);
if (result == 0)
return -1;
float cents = round(change * 100);
printf("Cents is %f",cents);
If the decimal separator is an issue, the above program will not output anything, because scanf()
will return 0
, and hence ok
will be 0
after you call the function.
One important consequence of ignoring the return value of non-void
functions is that if the value was not initialized like in this case with scanf()
, and you don't know that because you didn't check the return value, then undefined behavior will happen, meaning that your program will contain bugs that are very difficult to find and hence very hard to fix.