十进制到二进制转换器(整数1-8)

问题描述:

数字4,5,6,7和8不断返回不正确的值,如20,21和31。任何人都可以帮忙吗?谢谢!我试图将十进制数转换为二进制数,并且正在使用整数1-8。十进制到二进制转换器(整数1-8)

// This program converts whole numbers from 1 to 8 to their binary equivalent. 
#include <iostream> 
using namespace std; 

int main() 
{ 
    int decimal; 
    int binary; 
    int remainder1; 
    int remainder2; 
    int remainder3; 
    int remainderA; 
    int remainderB; 
    int remainderC; 
// Get the decimal to convert. 
cout << "Enter a whole number between 1 and 8: "; 
cin >> decimal; 

if (decimal==1) 
{ 
     binary = decimal/1; 
     cout << binary; 
    } 
else if (2 <= decimal < 4) 
{ 
     remainder1=decimal%2; 
     remainderA=decimal/2; 
     binary=remainder1/1; 
     cout << remainderA <<binary; 
    } 
else if (4 <= decimal < 8) 
{ 
     remainder2=decimal%4; 
     remainderA=decimal/4; 
     remainder1=remainder2%2; 
     remainderB=remainder2/2; 
     binary=remainder1/1; 
     cout << remainderA <<remainderB <<binary; 
    } 
else if(decimal==8) 
{ 
     remainder3=decimal%8; 
     remainderA=decimal/8; 
     remainder2=remainder3%4; 
     remainderB=remainder3/4; 
     remainder1=remainder2%2; 
     remainderC=remainder2/2; 
     binary=remainder1/1; 
     cout <<remainderA<<remainderB<<remainderC<<binary<<endl; 
    } 
} 
+3

解决这些问题的正确工具是你的调试器。在*堆栈溢出问题之前,您应该逐行执行您的代码。如需更多帮助,请阅读[如何调试小程序(由Eric Lippert撰写)](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/)。至少,您应该\编辑您的问题,以包含一个[最小,完整和可验证](http://*.com/help/mcve)示例,该示例再现了您的问题,以及您在调试器。 –

表达式像2 <= decimal < 4,而有效的语法,不要做你认为他们做的。

改写为2 <= decimal && decimal < 4

正式地,2 <= decimal < 4被评估为(2 <= decimal) < 4,归因于相关性。这是true < 4false < 4,在两种情况下均为true。这解释了为什么你的代码从4开始分解。

您的测试if(4 <= decimal < 8)是不是你的意思, 你需要写if((4 <= decimal) && (decimal < 8))

什么if(4<= decimal < 8)方法是:

  • 声明中介变量(称之为value

  • 1 )将4与小数进行比较,如果小数点< = 4,则值= 1 else值 = 0

  • 2)如果(价值< 8)然后...