Search code examples
cfloating-pointfloating-point-conversion

Getting wrong output from a simple floating point calculation


Possible Duplicate:
C++: What is the printf() format spec for “float”?

I am absolutely new to programming, just a starter level (still very novice and error-prone :)

The question that I have is as follows. I am writing a program in C to transform 27 degrees F into Celsius.

The code is below:


int main (void)

{
    float F = 27;
    float C = (F - 32) / 1.8;

    printf ("27 degrees Fahrenheit is %i degrees Celsius ", C);

    return 0;    
}

Getting the following output:

27 degrees Fahrenheit is -2147483648 degrees Celsius

I didn't expect that turns out that cold. That should be -2.77 by my calculator. What might be wrong? As a result of such calculations the world might freeze up! ))

I guess that is fundamentals I am asking about, but sounds interesting to me. Appreciate your help.


Solution

  • printf ("27 degrees Fahrenheit is %f degrees Celsius ", C);
    

    %i is the format specifier for int. For passing a double or a float, you need %f.