所以我一直在为我的 C++ 类(class)开发一个项目,我们必须创建一个二进制计算器。然而教授说这些函数应该返回一个 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 += (num % 2 == 0 ? "0" : "1");
应该是
bin = (num % 2 == 0 ? "0" : "1") + bin;
因为你每次都将 num
的最低有效位添加到字符串中。所以最后,根据您的代码,您将拥有最不重要的最左边而不是最右边。
编辑:为了将结果截断为 8 位宽度,请更改以下行:
return first + second;
由这一个:
return (first + second) & 0xFF; // Same as (first + second) % 256
关于c++ - 二进制集合计算器函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27456428/