C++温度转换程序接收用户输入后异常终止问题求助
华氏度与摄氏度转换程序运行异常问题
我写了一个实现华氏度与摄氏度互转的C++程序,代码如下:
#include "util.h" #include <cmath> double celsius(double t) { double C = (t-32) * 5/9; C = round(C); return C; } double fahrenheit(double t) { double F = t * 9/5 + 32; F = round(F); return F; } double round(double num) { double rounded = round(num); return rounded; } int main() { double temp = readDouble("Please enter a temperature: "); string type = readLine("Enter C to convert to Celsius or F to convert to Fahrenheit: "); if(type == "C") { double convertedTemp = celsius(temp); cout << temp << " degrees Celsius is " << convertedTemp << " degrees Farenheit"; } else if(type == "F") { double convertedTemp = fahrenheit(temp); cout << temp << " degrees Fahrenheit is " << convertedTemp << " degrees Celsius"; } return 0; }
程序运行时,输入转换类型(C或F)后直接停止,不执行后续的if语句逻辑。排查后发现程序卡在string type = readLine("Enter C to convert to Celsius or F to convert to Fahrenheit: ");这一步,尝试过添加system("pause")或在return前加cin >> randomVariable都没用。想问这是代码问题还是CodeHS平台的问题?
问题分析与修复方案
自定义
round函数触发无限递归
你自己实现的round函数内部直接调用自身,会导致无限递归,最终造成程序栈溢出崩溃。且你已经引入了<cmath>,直接使用标准库的std::round即可,无需重复实现。输入缓冲区残留换行符干扰
readDouble读取浮点数后,输入缓冲区会残留换行符,后续readLine会直接读取这个空换行,导致type为空字符串,后续if判断无法匹配,看起来像程序停止运行。整数除法导致精度丢失
代码中的5/9、9/5是整数除法,结果会被截断为0,导致转换计算完全错误,需改为浮点数除法5.0/9.0、9.0/5.0。拼写错误
输出语句里的Farenheit是拼写错误,正确应为Fahrenheit。
修复后的代码
#include "util.h" #include <cmath> #include <limits> double celsius(double t) { double C = (t - 32) * 5.0 / 9.0; C = std::round(C); return C; } double fahrenheit(double t) { double F = t * 9.0 / 5.0 + 32; F = std::round(F); return F; } int main() { double temp = readDouble("Please enter a temperature: "); // 清空输入缓冲区残留的换行符 std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); string type = readLine("Enter C to convert to Celsius or F to convert to Fahrenheit: "); if(type == "C") { double convertedTemp = celsius(temp); cout << temp << " degrees Celsius is " << convertedTemp << " degrees Fahrenheit"; } else if(type == "F") { double convertedTemp = fahrenheit(temp); cout << temp << " degrees Fahrenheit is " << convertedTemp << " degrees Celsius"; } return 0; }
关于CodeHS平台的疑问
修复上述代码问题后如果仍出现异常,再考虑平台因素,但目前代码中的核心错误足以导致程序运行异常,优先修复代码即可。
内容的提问来源于stack exchange,提问作者jk867
相关产品推荐
相关产品推荐

