【发布时间】:2018-03-08 04:54:00
【问题描述】:
该程序适用于任何给定长度的无符号整数,但对于负整数,如果整数为 -99 且长度为 8,则输出为 10011100,但正确答案为 10011101。所以,基本上,“+1”步骤不见了。如何在不添加新库或使用数组的情况下对其进行编码?
$
#include <iostream>
#include "math.h"
#include <string>
using namespace std;
// DONT MAKE ANY ADDITION
// DONT USE ANY ARRAY DATA TYPE
string decimalToTwoComplimentString(int a, int length)
{
int bitSize=0;
string binary, r_bin;
for(int j=abs(a); j>=0; j/=2)
{
if(a>=0) // NO PROBLEM HERE
{
if(bitSize!=length)
{
if(j%2==0)
binary.append("0");
else if(j%2==1)
binary.append("1");
bitSize++;
}
else if(bitSize==length)
{
break;
}
}
else if(a<0) // ADDING +1 AT THE END PART IS MISSING!
{
if(bitSize!=length)
{
if(j%2==0)
binary.append("1");
else if(j%2==1)
binary.append("0");
bitSize++;
}
else if(bitSize==length)
{
break;
}
}
}
for(int i=binary.length()-1; i>=0; i--) // PRINTING STRING BACKWARDS
{
r_bin+=binary.at(i);
}
return r_bin;
}
int main()
{
int L;
cout<< "Enter bit pattern size";
cin>>L;
int a, b;
cout<<"Enter an integer a ";
cin>>a;
cout<<"Enter an integer b ";
cin>>b;
int c1 = a + b;
cout<<"In decimal "<< a << " + " << b << " is " << c1 << endl;
string A = decimalToTwoComplimentString(a, L);
string B = decimalToTwoComplimentString(b, L);
cout<< "The Two's complement of " << a << " is \t" << A << endl;
cout<< "The Two's complement of " << b << " is \t" << B << endl;
system("Pause");
return 0;
}
【问题讨论】:
-
您尝试了哪些方法,为什么无法弄清楚?只需将结果视为无符号整数并加 1。没有人说您必须将所有内容放在一个大循环中。不过,您的代码中有一些奇怪的逻辑,例如在循环内部而不是外部检查数字是否为负数,这会导致在每次迭代而不是仅在开始时进行检查。
-
我不知道这里有什么问题。二进制补码(不是compliment)加减法与无符号版本完全相同,因此不需要单独的加法器
标签: c++ string twos-complement