【发布时间】:2014-12-25 06:38:18
【问题描述】:
所以我一直在为我的 C++ 课程做一个项目,我们必须创建一个二进制计算器。然而,教授说这些函数应该返回一个 8 位二进制集。我的问题是这个
11111111 + 11111111 = 0111111110
然而在我们最初创建的函数中,这就是结果
11111111 + 1111111 = 00000000
这对我来说是不正确的。所以我把我的功能改成了这个
十进制转二进制
string DecToBin(int num)
{
/*
Purpose: Changing a Decimal to a Binary Set
Pre: Valid positive integer
Post: Returns the valid binary string
*/
string bin = "";
while (num >= 0)
{
bin += (num % 2 == 0 ? "0" : "1");
if (num != 0)
num /= 2;
else break;
}
return bin;
}
虽然问题又来了
01010101 + 10101010 = 011111111
但我上面的函数返回
01010101 + 10101010 = 111111110
如果我需要返回一个 8 位集合,或者如果像我上面所说的函数一样,它为某些返回正确答案,而为其他返回错误,我需要弄清楚为什么会这样首先。
二进制转十进制
int BinToDec(string bin)
{
/*
Purpose: To generate a decimal integer from a string binary set
Pre: Valid String binary set
Post: Output the output decimal integer
*/
int output = 0; //initialize output as 0
int base2Start = 128;//base2 start at 128
int len = bin.length();//get the string length
for (int i = 0; i < len; i++)//iterate
{
if (bin[i] == '1')//if bin[i] in the array of string is a char 1
{
output = output + base2Start;//output gets + base2Start
}//end if condition
base2Start = base2Start / 2;//divide base2Start after each iteration
}//end for loop
return output;//return the output
}
加法函数
int Addition(string st1, string st2)
{
/*
Purpose: Get's two valid Binary sets, then adds their decimal conversion, and returns the addition
Pre: Need two strings that SHOULD be valid binary
Post: Returns binary from decimal conversion
*/
int first, second;
if (ValidBin(st1))
{
first = BinToDec(st1);
}
else return 0;
if (ValidBin(st2)){
second = BinToDec(st2);
}
else return 0;
add++;
return first + second;
}
【问题讨论】:
-
你做二进制或运算的代码在哪里?另外,您不认为您的 bin 应该反向以获得十进制数的正确二进制表示吗?
-
更新了更多的表现形式和其他功能