函数声明问题,K&R问题1-15

Problem with function declaration, K&R problem 1-15

最初对于华氏度的多个值,华氏度到摄氏度存在问题。 现在在问题 1-15 中我们必须使用一个函数来完成这个任务。 以下是我的代码:

 #include<stdio.h>

float temp_conv(float n);

int main()
{
    float lower, upper, step;
    int i;

    lower= 0;
    upper= 300;
    step= 20;
    
    for(i=0; i<=(upper-lower)/step; ++i)
        printf("%5.1f\t%6.2f\n", i*step, temp_conv(i*step));
}

float temp_conv(float n)
{
    float fahr, celsius;
    
    celsius= (5.0/9.0)*(fahr-32.0);

    return celsius;
}

并产生以下输出:

  0.0   -17.78
 20.0   -17.78
 40.0   -17.78
 60.0   -17.78
 80.0   -17.78
100.0   -17.78
120.0   -17.78
140.0   -17.78
160.0   -17.78
180.0   -17.78
200.0   -17.78
220.0   -17.78
240.0   -17.78
260.0   -17.78
280.0   -17.78
300.0   -17.78

我在函数 temp_conv 中传递了不同的值,但它也产生了 0 华氏度的转换值。也许这个函数有问题,但是它是如何计算 0 华氏度的摄氏度值的?

请帮忙。

float temp_conv(float n) {
    float fahr, celsius;
    celsius = (5.0/9.0)*(fahr-32.0);
    return celsius;
}

您忽略传递给函数的参数 n 并从 fahr 计算 celsiusfahr 未初始化(没有 fahr = something),它有一些未初始化的垃圾值恰好导致 -17.78.

只需根据参数计算即可:

float temp_conv(float n) {
    float celsius;
    celsius = (5.0 / 9.0) * (n - 32.0);
    return celsius;
}

或更好的命名:

float temp_conv(float fahr) {
    float celsius;
    celsius = (5.0 / 9.0) * (fahr - 32.0);
    return celsius;
}

或者真的只是:

float temp_conv(float fahr) {
    return (5.0 / 9.0) * (fahr - 32.0);
}