C: converting Farenheit to Celsius

不问归期 提交于 2019-11-27 09:53:23

The scanf call uses the wrong format string. You are reading an int so you need it to be:

scanf("%d", &fahrenheit);

The expression 5/9 is evaluated using integer division. In fact the compiler can work it out at compile time. That expression evaluates to 0.

You need to perform floating point division. For instance:

5.0/9

Or:

5/9.0

Or

5.0/9.0

You just need at least one operand to be a floating point value.

Putting this into your expression, you can write:

c = 5.0/9.0 * (fahrenheit - 32);

and obtain the answer that you expect.


Your printf statement is wrong too. You should enable warnings and let the compiler tell you that. You meant to write:

printf("Here is your %f in celsius!.\n", c);

Integer math versus floating point math.

i = 5/9           // i is equal to 0
d = 5.0/9.0       // d is equal to whatever 5 divided by 9 would actually be

You also need to actually print the value:

printf("Here is your %f in celsius!.\n", c);
Taum

Short answer: Operations on integers return integers even if the variable you store the result on is a double. Divisions between integers are truncated.

You should write this instead:

c = 5.0/9.0 * (fahrenheit - 32.0);

Adding a ".0" (or even just a ".") to your constant makes them floating point values.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!