将华氏温度转换为摄氏温度的C程序始终打印为零

Jam*_*mes 8 c

我需要一些帮助,用于将华氏温度转换为C摄氏温度的程序.我的代码看起来像这样

#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;
}
Run Code Online (Sandbox Code Playgroud)

每次执行它时,结果为0.000000.我知道我错过了什么,但无法弄清楚是什么.

nyb*_*ler 23

5/9将导致整数除法,其将= 0

试试吧5.0/9.0.

  • @Foo Bah - 也许,但避免尽可能多的隐式转换是一个很好的策略.编译器为您更改的类型越少,您的意外就越少. (6认同)
  • 从技术上讲,5/9.0就足够了 (3认同)

Inc*_*ito 9

你的问题在这里:

celsius = (5/9) * (fahrenheit-32);
Run Code Online (Sandbox Code Playgroud)

5/9永远都会给你0.改用Use(5.0/9.0).