C++编写二进制十进制转换菜单时输出结果始终为0问题求助
问题原因
你的代码存在两个核心问题导致输出异常:
- 浮点精度错误:你调用的
pow()是<cmath>库专为浮点数设计的计算函数,返回值为double类型,受浮点精度限制,经常出现类似pow(10,1)=9.9999999999的计算误差,赋值给整型变量时会被直接截断为9,最终导致计算结果完全错误。 - 原代码菜单选项的
Deciml存在拼写错误,已在修复版中修正为Decimal。
修复方案
将pow浮点运算替换为纯整数权重累加逻辑,每次循环手动更新权重值,彻底规避浮点误差问题。
修复后完整代码
#include<iostream> using namespace std; int main() { int dec,ch; long bin,temp,weight; do { dec=bin=ch=0; cout<<"\n\n\t\tMENU\n1. Decimal to Binary number\n2. Binary to Decimal number\n3. Exit\n"; cout<<"Enter your choice(1/2/3)> "; cin>>ch; switch(ch) { case 1: cout<<"Enter a decimal number: "; cin>>dec; temp=dec; weight = 1; while(dec) { bin += (dec%2)*weight; dec /= 2; weight *=10; } cout<<temp<<" in decimal = "<<bin<<" in binary"<<endl; break; case 2: cout<<"Enter a binary number: "; cin>>bin; temp=bin; weight = 1; while(bin) { dec += (bin%10)*weight; bin /= 10; weight *=2; } cout<<temp<<" in binary = "<<dec<<" in decimal"<<endl; break; case 3: break; default: cout<<"Invalid choice"<<endl; } }while(ch!=3); return 0; }
运行效果
修复后所有运算均为整数运算,无精度损失:
- 输入十进制
23会正确输出二进制10111 - 输入二进制
11001会正确输出十进制25,不会再出现输入值显示为0的异常
内容的提问来源于stack exchange,提问作者JRBros
相关产品推荐
相关产品推荐

