I am working on a program that will convert from dollars to cents. I take in user input as a float using a predefined function then i try to multiply this float by 100 but it gives me an incorrect value. Heres the code:
printf("Change in dollars: ");
change= GetFloat();
cents= round(change*100);
printf("Cents is %f",cents);
This is a logical error because the program runs fine but there is something wrong with the mathematics for example if i enter 1.50 when prompted, the return i get is 1004 which is clearly wrong. What i want to happen is 150 to be outputted.
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 ofscanf()
"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
which you would call like this
If the decimal separator is an issue, the above program will not output anything, because
scanf()
will return0
, and henceok
will be0
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 withscanf()
, 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.