【问题标题】:int produces near correct answer, but float just gives -18.000int 产生接近正确的答案,但 float 只给出 -18.000
【发布时间】:2015-07-02 00:55:49
【问题描述】:

我编写了一个简单的程序,使用函数将华氏度转换为摄氏度(使用 Python 工作了 2 周,想刷新一下自己):

#include <stdio.h>
#include <math.h>

int temp_change(fahrenheit);

int main()
{
    while(1)
    {
        int fahrenheit;
        printf("Please input a temperature in Fahrenheit.\n");
        scanf("%d", &fahrenheit); //Obtains degrees F value
        printf("%d\n", temp_change(fahrenheit));

    }
}
//Function to change temperature
int temp_change(fahrenheit)
{
    int centigrade;
    centigrade = 5*(fahrenheit - 32)/9; //Changing the temperature
    return centigrade;
}

它给了我正确的答案(最接近的程度)。但是,我想要确切的答案,所以我将所有的 ints 更改为 floats(int main() 除外。现在程序会给我的唯一的东西是 -18.000000,不管我给它什么输入。 总结我尝试过的最佳方式:我尝试了 ints 和 floats 的不同组合,但没有运气。 我怀疑它与printf("%d\n", temp_change(fahrenheit)); 有关,但是当一切都是int 时,它给了我正确的答案,所以我不知道。 XD 提前感谢您的帮助!

【问题讨论】:

  • 很可能您在转换所有数据类型时忽略了更改scanf()printf() 格式。对于float 参数,您需要%f 而不是%d
  • 想通了——需要将函数定义中的变量初始化为float
  • @JohnBollinger 谢谢,但不,那会给我一个错误。
  • @JohnBollinger 我正在使用 dev c++,如果我“在转换所有数据类型时忽略了更改 scanf() 和 printf() 格式”会给我一个错误/警告.我需要做的是float temp_change(float fahrenheit)。看到了吗?
  • 谁知道用Python两周能有这样的效果。

标签: c floating-point integer temperature


【解决方案1】:

整数版本不会为您提供最接近的转换温度,它会将温度四舍五入到0

您的代码中还有一个问题:temp_change 的原型不完整,您忘记指定参数的类型。

这是一个使用浮点数的更正版本:

#include <stdio.h>

float temp_change(float fahrenheit);

int main(void) {
    for (;;) {
        float fahrenheit;
        printf("Please input a temperature in Fahrenheit.\n");
        if (scanf("%f", &fahrenheit) == 1) {//Obtains degrees F value
            printf("%f\n", temp_change(fahrenheit));
        }
    }
}
//Function to change temperature
float temp_change(float fahrenheit) {
    float centigrade;
    centigrade = 5 * (fahrenheit - 32) / 9; //Changing the temperature
    return centigrade;
}

请注意,您确实应该使用double 精度浮点数。顺便提一下,temp_change() 的返回值在传递给printf 时会转换为double。格式说明符%f 采用float* 表示scanf,但采用double 表示printf

【讨论】:

  • 非常感谢!我已将您的答案选为正确答案。
【解决方案2】:

您需要更改转换功能。像这样

float temp_change(fahrenheit)
{
    float centigrade;
    centigrade = 5*(fahrenheit - 32)/9.0; //Changing the temperature
    return centigrade;
}

如果你愿意,你也可以在浮点数中输入。在这里

printf("%d\n", temp_change(fahrenheit));

使用 %f 而不是 %d

【讨论】:

  • 这仍然不正确:因为fahrenheit没有类型,所以它被认为是int。表达式5*(fahrenheit - 32)/9 被计算为int 并在存储到centigrade 时转换为float...你得到与int 版本相同的结果。
猜你喜欢
  • 2015-06-23
  • 1970-01-01
  • 2018-04-06
  • 1970-01-01
  • 1970-01-01
  • 2013-04-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多