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

时间:2016-09-19 12:40:58

标签: c++ binary decimal

第4,5,6,7和8号不断返回错误值,例如20,21和31.任何人都可以帮忙吗?谢谢!我试图将十进制数转换为二进制数,并使用整数,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;
    }
}

2 个答案:

答案 0 :(得分:3)

2 <= decimal < 4这样的表达虽然在语法上有效,但却没有按照你的想法行事。

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

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

答案 1 :(得分:1)

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

if(4<= decimal < 8)的含义是:

  • 声明一个中间变量(称之为value

  • 1)比较4和十进制,如果十进制&lt; = 4则值= 1其他值 = 0

  • 2)if(value&lt; 8)then ...