C语言温度转换程序报错:指针与整数比较问题求助
温度转换C程序错误修复方案
核心错误分析
- 指针与整数类型不匹配:
unit1、unit2是单个字符类型,但代码里把它们和Ferhenhite这类字符串数组直接比较——字符串数组在表达式中会退化为内存指针,单个字符属于整数类型,两者类型不匹配,直接触发「Comparison between pointer and integers」错误。 - scanf传参错误:
scanf("%c", unit1)没有传递变量地址,应该写成scanf("%c", &unit1),否则会导致非法内存访问。 - 输入缓冲区残留问题:读取温度后,输入缓冲区会留下换行符,后续的
scanf("%c")会直接读取这个换行符,导致无法获取用户实际输入的单位。 - 整数除法逻辑错误:
5/9这类整数除法在C中结果为0,完全破坏温度计算精度,必须改为浮点除法。 - 分支文本笔误:Kelvin转Celcius的分支里,输出文本错误写成了“ferhenhite”,属于逻辑外的低级错误。
修复后的完整代码
#include <stdio.h> #include <string.h> // 用于字符串比较函数strcmp int main(){ double temp; // 用字符串存储单位,避免单个字符输入的歧义 char unit1[20], unit2[20]; const char Fahrenheit[] = "Fahrenheit", Celcius[] = "Celcius", Kelvin[] = "Kelvin"; printf("Enter the degree temperature you want to convert: "); scanf("%lf", &temp); // 清除温度输入后残留的换行符 getchar(); printf("Select the degree of temperature for the entered temperature. (Fahrenheit/Celcius/Kelvin): "); fgets(unit1, sizeof(unit1), stdin); // 去掉fgets自动读取的换行符 unit1[strcspn(unit1, "\n")] = '\0'; printf("Select the degree of temperature to be converted for the entered temperature. (Fahrenheit/Celcius/Kelvin): "); fgets(unit2, sizeof(unit2), stdin); unit2[strcspn(unit2, "\n")] = '\0'; if (strcmp(unit1, Fahrenheit) == 0) { if (strcmp(unit2, Celcius) == 0) { printf("The entered temperature in celcius is: %.2lf°\n", 5.0/9 * (temp - 32)); } else if (strcmp(unit2, Kelvin) == 0) { printf("The entered temperature in kelvin is: %.2lf°\n", (temp + 459.67) * 5.0/9); } else { printf("You have entered wrong target unit\n"); } } else if (strcmp(unit1, Celcius) == 0) { if (strcmp(unit2, Fahrenheit) == 0) { printf("The entered temperature in fahrenheit is: %.2lf°\n", (9.0/5)*temp + 32); } else if (strcmp(unit2, Kelvin) == 0) { printf("The entered temperature in kelvin is: %.2lf°\n", temp + 273.15); } else { printf("You have entered wrong target unit\n"); } } else if (strcmp(unit1, Kelvin) == 0) { if (strcmp(unit2, Celcius) == 0) { printf("The entered temperature in celcius is: %.2lf°\n", temp - 273.15); } else if (strcmp(unit2, Fahrenheit) == 0) { printf("The entered temperature in fahrenheit is: %.2lf°\n", (temp - 273.15) * 9.0/5 + 32); } else { printf("You have entered wrong target unit\n"); } } else { printf("You have entered wrong source unit\n"); } return 0; }
关键修复说明
- 字符串比较替换:改用
strcmp函数做字符串相等判断(需引入<string.h>),彻底解决指针与字符的类型不匹配问题。 - 输入逻辑优化:用
fgets读取完整单位字符串,配合strcspn去掉换行符;用getchar清除温度输入后的残留换行,确保输入内容准确。 - 除法精度修正:把
5/9改为5.0/9,触发浮点除法,保证温度计算的精度。 - 分支完整性补充:每个主分支都增加了目标单位合法性判断,避免非法输入导致的逻辑混乱;同时修正了输出文本的笔误。
- 拼写修正:把
Ferhenhite改为标准拼写Fahrenheit(若需保留原拼写,直接改回即可,不影响功能)。
内容的提问来源于stack exchange,提问作者tuklu
相关产品推荐
相关产品推荐

