Question

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.

Was it helpful?

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.

OTHER TIPS

In your printf() you are specifying that the memory that C points to should be interpreted as if it was an int (32 or 64 bit depending on your system and compiler). But the real value stored in that memory location is a float.

So the printf() gets confused and outputs what would be an int value of the bits in the memory used for float

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top