【问题标题】:Decimal to Binary Converter (Whole numbers 1-8)十进制到二进制转换器(整数 1-8)
【发布时间】:2017-01-27 03:51:14
【问题描述】:

数字 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;
    }
}

【问题讨论】:

标签: c++ binary decimal


【解决方案1】:

2 &lt;= decimal &lt; 4 这样的表达式虽然在语法上是有效的,但不要做你认为他们做的事情。

改写为2 &lt;= decimal &amp;&amp; decimal &lt; 4

由于关联性,正式地,2 &lt;= decimal &lt; 4 被评估为(2 &lt;= decimal) &lt; 4。这是true &lt; 4false &lt; 4,在这两种情况下都等于true。这就解释了为什么你的代码从 4 开始就崩溃了。

【讨论】:

    【解决方案2】:

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

    if(4&lt;= decimal &lt; 8) 的意思是:

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

    • 1) 将 4 与十进制比较,如果十进制

    • 2) if(value

    【讨论】:

      猜你喜欢
      • 2016-08-26
      • 1970-01-01
      • 2020-06-27
      • 2020-06-25
      • 2012-05-28
      • 2013-05-14
      • 2023-04-11
      • 2021-07-29
      • 2019-07-18
      相关资源
      最近更新 更多