Float not being converted correctly

84 Views Asked by At

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.

1

There are 1 best solutions below

2
On BEST ANSWER

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.