c++ 二进制问题请教
以下程序针对二进制补码算术中整数的算术运算问题,要求先确定一个bit pattern size ,然后第一个函数要把输入的两个整数转化为二进制输出,第二个函数把两个二进制数相加输出,第三个函数再把结果转化回十进制。
只使用c++字符串数据类型,不使用任何数组变量。不改变主程序也不更改函数名,实现缺失函数,使程序运行正确。可编写额外的帮助函数,从函数中调用但不能对程序做修改。
需要使用c++字符串数据类型来表示这两个二进制补码的表示形式,不能使用任何数组变量,可使用字符串变量作为一个整体或使用索引访问字符串中变量中的字符。
程序示例运行如下
输入位模式大小的正整数:5
输入整数A:9
输入整数B:-14
十进制 9 + -14 = -5
二进制补码9 是 01001
二进制补码-14 是 10010
01001和10010的二进制和是11011。
在二进制补码计算中,9+ -14=-5。
#include iostream>
#include cmath>
#include string>
using namespace std;
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 = decimalToTwocomplementString(a, L);
string B = decimalToTwocomplementString(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 = TwoComplementStringAddition(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 = TwoComplementStringToDecimal(C);
cout << "In two's complement arithmetic, " << a << " + " << b << " is " << c2 << endl;
//Print some concluding results
if (c1 == c2) cout << c1 << " is equal to " << c2 << ". Good Job!" << endl;
else
{
cout << c1 << " is not equal to " << c2 << endl;
cout << "Either " << c1 << " cannot be represented by the given bit pattern OR we have made some mistake!" << endl;
}
system("Pause");
return 0;
}
原程序拷屏如下: