C++整数进制转换程序输出异常字符,求错误排查
问题分析与修复
你的代码出现错误的核心原因有两个:
1. 整数溢出导致数值错乱
你定义的sum是int类型,而输入的十进制数4136490862已经超过了32位int的最大值(2147483647),这会导致sum溢出,变成错误的负数或乱码值。后续对这个错误值进行取模、除法操作,自然会生成完全错误的结果。
解决方法:将sum的类型改为long long,它能容纳更大的整数范围(64位long long最大值为9223372036854775807),足以处理你的测试用例。
2. 使用pow函数带来的精度误差
pow是C++标准库中的浮点数运算函数,用来计算整数幂时可能出现精度丢失。比如计算pow(10,9)时,实际返回值可能是999999999.9999999而非精确的1000000000,当你把这个浮点数转换为整数时,会被截断成错误的数值,导致sum计算不准确。
解决方法:用整数循环的方式计算幂次,避免浮点数精度问题。比如初始化一个power变量为1,每次循环后乘以currentBase,而不是调用pow。
修改后的代码
#include <iostream> #include <string> #include <cctype> // 补充字符判断函数所需的头文件 int main(void){ std::string num; int currentBase; int newBase; int lastDigit; long long sum = 0; // 改为long long避免溢出 long long power = 1; // 用整数变量计算幂次 int remainder; std::string new_number = ""; // 获取原进制 std::cout <<"Please enter the number's base: "; std::cin >> currentBase; // 获取对应进制的数字 std::cout <<"Please enter the number: "; std::cin >> num; // 获取目标进制 std::cout <<"Please enter the new base: "; std::cin >> newBase; // 校验进制有效性(2-36) if ((currentBase < 2) || (currentBase > 36) || (newBase < 2) || (newBase > 36)){ std::cout << "One or more of the bases that you entered are not valid!" << std::endl; return 1; } // 将输入字符串转换为十进制 for(int j = num.size() - 1; j >= 0; j--) { char c = num[j]; if (isdigit(c)) { lastDigit = c - '0'; } else if (isupper(c)) { lastDigit = c - 'A' + 10; } else if (islower(c)) { lastDigit = c - 'a' + 10; } sum += lastDigit * power; power *= currentBase; } // 将十进制转换为目标进制 if (sum == 0) { new_number = "0"; // 处理输入数字为0的特殊情况 } else { while (sum != 0) { remainder = sum % newBase; if (remainder < 10) { new_number = std::to_string(remainder) + new_number; } else { new_number = char(remainder - 10 + 'A') + new_number; } sum /= newBase; } } // 输出结果 std::cout << num << " base " << currentBase << " is " << new_number << " base " << newBase << std::endl; return 0; };
内容的提问来源于stack exchange,提问作者ryan
相关产品推荐
相关产品推荐

