【发布时间】: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;
}
}
【问题讨论】:
-
调试器是解决此类问题的正确工具。 在询问 Stack Overflow 之前,您应该逐行逐行检查您的代码。如需更多帮助,请阅读How to debug small programs (by Eric Lippert)。至少,您应该 [编辑] 您的问题,以包含一个重现您的问题的 Minimal, Complete, and Verifiable 示例,以及您在调试器中所做的观察。