c - 不断得到 0.00 作为答案

标签 c

最后我一直收到 0 作为我的答案。请帮忙

#include <stdio.h>
int Fahrenheit = 0;
double Celsius = 0.0;
double main(void)
{
    printf("This program will convert the temperature from fahrenheit to celsius.\n");
    printf("Please type in the temperature in fahrenheit followed by the enter key.\n");
    scanf("%d%",&Fahrenheit);
    Celsius = (5/9) * (Fahrenheit-32) ;
    printf("Your temperature in celsius is %3.2f.\n", Celsius);

    return(0);
}

最佳答案

由于整数除法,将5/9更改为5.0/9.0。另外,将 Fahrenheit double 并将 scanf() 更改为

if (scanf("%lf", &Fahrenheit) == 1)
{
    Celcius = 5.0 * (Fahrenheit - 32.0) / 9.0;
    printf("Your temperature in celsius is %3.2f.\n", Celsius);
}

另外:

  1. 绝对没有理由将变量设置为全局变量。
  2. 我看到了许多奇特的 main() 签名,现在

    double main(void);
    
  3. 忽略 scanf() 的返回值将导致潜在的未定义行为。如果我有一位老师禁止 if 语句但需要 scanf(),我会放弃他并找到一位好的老师。

    但是当然,如​​果我正在学习,我怎么知道忽略 ٰscanf() 的返回值是不好的?这就是可悲的部分,许多人甚至不知道它返回一个值或它失败,例如尝试这个

    int value;
    if (scanf("%d", &value) != 1)
        fprintf(stderr, "Error, invalid input\n");
    else
        fprintf(stdout, "Ok, so your input is `%d'\n", value);
    

    输入“abcd”而不是数字,会发生什么?

关于c - 不断得到 0.00 作为答案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35257538/

相关文章:

c - 为什么我无法在 for 循环中计算 "array to NULL"?

c - 在这种特殊情况下如何处理管道

c - GCC ARM C 编译器不遵守 -std=c99 的 %llx printf 格式化代码

c - C 中的 exit(0) 和 exit(1) 有什么区别?

c - 从二维数组打印字符

c - 将地址传递给函数并将其分配给另一个变量

c - 如何获取目录中最后n个文件

c - 如何输入两个中间有破折号的整数?

c - 通过 cmake 添加带有变量的宏

c - 释放指针内存后,我可以重新分配值