我创建了一个小程序来将温度单位从 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;
}