Reputation: 33
#include<stdio.h>
main()
{
int fahr;
for(fahr = 300; fahr >= -40; fahr = fahr - 20)
printf("%3.d %8.d\n ",fahr,(5.0/9.0) * (fahr - 32.0));
}
It prints the equivalent values but all wrong. Why is it happening?
Upvotes: 3
Views: 70
Reputation: 224457
The expression that converts to Celsius uses constants of type double
so the expression is of type double
. Because you're using the %d
format specifier with a double
value, you get undefined behavior.
Change the second format specifier to %8.f
and you'll get the expected output. Also, change the first format specifier to %3.1d
so that when fahr
is 0
it will print the value instead of just blanks.
printf("%3.1d %8.f\n ",fahr,(5.0/9.0) * (fahr - 32.0));
Upvotes: 3
Reputation: 118
Because you trying to use double, where you need to use float. Try this:
#include<stdio.h>
main()
{
int fahr;
for(fahr = 300; fahr >= -40; fahr = fahr - 20)
printf("%3.d %8.f\n ",fahr,((fahr - 32) * .5556));
}
Upvotes: 1