C program to convert Fahrenheit to Celsius

2019-01-01 02:45发布

I'm writing a program for a class I'm in and need some help with a program for converting Fahrenheit to Celsius in C. My code looks like this

#include <stdio.h>
int main (void)
{

int fahrenheit;
double celsius;

printf("Enter the temperature in degrees fahrenheit:\n\n\n\n");
scanf("%d", &fahrenheit);
celsius = (5/9) * (fahrenheit-32);
printf ("The converted temperature is %lf\n", celsius);

return 0;

}

Every time I execute it it the result is 0.000000. I know I'm missing something but can't figure out what.

标签: c
8条回答
素衣白纱
2楼-- · 2019-01-01 02:58

When dealing with floats, it needs to be 5.0f / 9.0f.

When dealing with doubles, it needs to be 5.0 / 9.0.

When dealing with integers, remainders/fractions are always truncated. 5 / 9 results between 0 and 1, so it is truncated to just 0 every time. That multiplies the other side by zero and completely nullifies your answer every time.

查看更多
流年柔荑漫光年
3楼-- · 2019-01-01 03:01

You need to use floating point arithmetic in order to perform these type of formulas with any accuracy. You can always convert the final result back to an integer, if needed.

查看更多
十年一品温如言
4楼-- · 2019-01-01 03:03

You problem is here :

celsius = (5/9) * (fahrenheit-32);

5/9 will always give you 0. Use (5.0/9.0) instead.

查看更多
泛滥B
5楼-- · 2019-01-01 03:05

5 and 9 are of int type
hence 5/9 will always result 0.

You can use 5/9.0 or 5.0/9 or 5.0/9.0

You can also check C program for converting Fahrenheit into Celsius

查看更多
何处买醉
6楼-- · 2019-01-01 03:06

5/9 will result in integer division, which will = 0

Try 5.0/9.0 instead.

查看更多
浮光初槿花落
7楼-- · 2019-01-01 03:11

try celsius = ((double)5/9) * (fahrenheit-32); Or you can use 5.0.

The fact is that "/" looks at the operand type. In case of int the result is also an int, so you have 0. When 5 is treated as double, then the division will be executed correctly.

查看更多
登录 后发表回答