我真的是C ++的新手,我对程序有些困惑。 该程序应该使用2个整数,并将它们转换为带有L大小的二进制补码字符串,但是当我运行该程序时,我总是得到字符串下标超出范围错误。 我可能有很多错误,如果你们能指出一些大错误,那就太好了。 我的程序:
string reverse(string s)
{
string x="";
for(int i=s.length()-1;i>=0;i--)
{
x += s[i];
}
return x;
}
string twosComplementStringAddition(string a,string b)
{
string c;
int count;
for(int i=0;i<a.length();i++)
{
if(count>0)
c[i]='1';
else if(a[i]=='1' & b[i]=='1')
{
c[i]='0';
count++;
}
else if((a[i]=='1' & b[i]=='0')|| (a[i]=='0' & b[i]=='1'))
c[i]='1';
else if(a[i]=='0' & b[i]=='0')
c[i]='0';
count=0;
}
return c;
}
string negative(string a)
{
for(int i=0;i<a.length();i++)
{
if(a[i]=='1')
a[i]='0';
else
a[i]='1';
}
reverse(a);
string x="1";
twosComplementStringAddition(a,x);
reverse(a);
return a;
}
string decimalToTwosComplementString(int a, int L)
{
string s="";
L= s.length();
int b;
for(int i=0;i<L-1;i++)
{
b=a%2;
if(b==1)
s[i]='1';
else if(b==0)
s[i]='0';
a=a/2;
}
reverse(s);
if(a<0)
{
negative(s);
return s;
}
else
return s;
}
int twosComplementStringToDecimal(string a)
{
int result=0;
if(a[0]=='0')
{
reverse(a);
for(int i=0;i<a.length();i++)
{
if(a[i]=='1')
{
result= result + pow(2,static_cast<float>(i));
}
else if(a[i]=='0')
{
result = result + 0;
}
}
}
else
{
negative(a);
int resulta=0;
reverse(a);
for(int i=0;i<a.length();i++)
{
if(a[i]=='1')
{
resulta= resulta + pow(2,static_cast<float>(i));
}
else if(a[i]=='0')
{
resulta = resulta + 0;
}
}
return resulta;
}
return result;
}
int main()
{
//Read in the bit pattern size
int L;
do
{
cout << "Enter positive integer for the bit pattern size ";
cin >> L;
}while (L <= 0);
//Read in two integers a and b
int a, b;
cout << "Enter an integer a ";
cin >> a;
cout << "Enter an integer b ";
cin >> b;
//Calculate the decimal arithmetic sum of a and b and print the result
int c1 = a + b;
cout << "In decimal " << a << " + " << b << " is " << c1 << endl;
//Compute the two's complement representations of a and b
//Each integer must be represented in L-bits pattern
//Also these two's complement representations must be returned as string data types
string A = decimalToTwosComplementString(a, L);
string B = decimalToTwosComplementString(b, L);
//Print the two's complement representations of a and b
cout << "The two's complement of " << a << " is\t " << A << endl;
cout << "The two's complement of " << b << " is\t " << B << endl;
//Compute the binary sum of the two's complement representations of a and b
//The result must be returned as L-bit pattern string data type
string C = twosComplementStringAddition(A, B);
//Print the two's complement representation binary sum
cout << "The binary sum of " << A << " and " << B << " is " << C << endl;
//Convert the two's complement representation binary sum to decimal and print
int c2 = twosComplementStringToDecimal(C);
cout << "In two's complement arithmetic, " << a << " + " << b << " is " << c2 << endl;
system("Pause");
return 0;
}
对于任何愿意帮助的人,谢谢您的宝贵时间! 编辑: 几个小时后,我终于使它生效了,谢谢你们帮助初学者!