-1

我创建了一个小程序来将温度单位从 C° 转换为 F。char 单位需要将“C”转换为“F”,反之亦然。为此,我char unit直接在我的函数中修改了地址temp。现在我对直接打印函数时 printf 的工作方式有点困惑。正是在这一行:

printf("%.1lf %c", temp(input, &unit), unit);

我的问题是即使我的函数已经修改了以下值,printf它仍在打印我未修改的值:结果/预期unitchar unit

我可以通过将函数值存储到双变量中并打印它来解决这个问题:

result = temp(input, &unit);
printf("%.1lf %c", result, unit);

有人可以向我解释一下我的上述逻辑哪里错了吗?
printf("%.1lf %c", temp(input, &unit), unit);在我看来,printf 先打印我的函数的值,然后再打印unit. 该unit值正在函数内部被修改,所以我不明白为什么它没有被修改。

非常感谢您的时间。

#include <stdio.h>

double temp(int, char *);

int main(void) {
    int input = 0;
    char unit = 'a';
    double result = 0.0;
    printf("Temperature unit:");
    scanf("%d %c", &input, &unit);
    printf("%.1lf %c", temp(input, &unit), unit);
}

double temp(int temp, char * unit) {
    double output = 0.0;
    
    //convert to C°
    if (*unit == 'F') {
        output = (((double)temp - 32) * 5 / 9);
        *unit = 'C';
    }
    else if (*unit == 'C') {
        output = (double)temp * 9 / 5 + 32;
        *unit = 'F';
    }
    else {
        printf("wrong unit");
    }

    return output;
}
4

2 回答 2

0

我上面的逻辑哪里错了(?)

错误在于“即使我的函数已经修改了 char 单位的值”。

参数的评估顺序temp(input, &unit)unit给定的顺序printf("%.1lf %c", temp(input, &unit), unit);没有定义。

unit可以在之前temp(input, &unit)或相反的方式进行评估。

于 2020-06-28T11:54:46.810 回答
0

printf("%.1lf %c", temp(input, &unit), unit);这是一个未定义的行为,因为调用的函数会更改(副作用)第二个参数。在这种情况下,你不能这样做。

你需要:

printf("%.1lf ", temp(input, &unit));
printf("%c", unit);

或者

double temperature = temp(input, &unit);
printf("%.1lf %c", temperature, unit);
于 2020-06-28T10:14:43.303 回答