22. 已知 x 和 y,用变形补码计算 x-y,同时指出结果是否溢出。 (1) x=11011,y=-11111 (2) x=10111,y=11011 (3) x=11011,y=-10011
24. 已知 x 和 y,用变形补码计算 x+y,同时指出结果是否溢出。 (1)x=11011,y=00011 (2)x=11011,y=-10101 (3)x=-10110,y=-00001
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
int question = 0;
string fu(string str) {
if (str[0] == '0') {
str.replace(0, 2, "11");
} else {
str.replace(0, 2, "00");
}
return str;
}
string fanMa(string str) {
for (int i = 2; i < str.length(); i++) {
if (str[i] == '0') {
str[i] = '1';
} else {
str[i] = '0';
}
}
return str;
}
// 正数的原码反码补码都一样, 负数补码是反码+1
string buMa(string str) {
if (str[0] == '1') {
str = fanMa(str);
int flag = 1; // 标记要进位1
for (int i = str.length() - 1; i >= 0; i--) {
if (str[i] == '0') {
if (flag) {
flag = 0;
str[i] = '1';
}
} else if (str[i] == '1') {
if (flag) {
str[i] = '0';
}
}
}
}
return str;
}
string minus1(string str) {
// 相当于找到最后一个1变成0,最后一个1前的0都变成1
int flag = -1;
for (int i = str.length() - 1; i >= 0; i--) {
if (str[i] == '0') {
if (flag) {
str[i] = '1';
}
} else if (str[i] == '1') {
if (flag) {
flag = 0;
str[i] = '0';
}
}
}
return str;
}
// 从补码转到原码
string B2Y(string str) {
string res;
if (str[0] == str[1]) {
if (str[0] == '0') {
res = " +";
res += str.substr(2);
} else {
res = " -";
res += minus1(str.substr(2));
res = fanMa(res);
}
} else {
if (str[0] == '0') {
res = "+";
res += str.substr(1);
} else {
res = "-";
res += minus1(str.substr(1));
res = fanMa(res);
}
}
return res;
}
void checkOverFlow(string str) {
if (str.substr(0, 2) == "01") {
cout << "正溢出" << endl;
} else if (str.substr(0, 2) == "10") {
cout << "负溢出" << endl;
} else {
cout << "未溢出" << endl;
}
}
// 输入X和Y的原码, 计算结果
string Cal(string X, string Y, char oper = '+') {
printf("\n(%d)\n", ++question);
X = buMa(X);
cout << "[X]补: " << X << endl;
if (oper == '-') {
Y = fu(Y);
}
Y = buMa(Y);
if (oper == '-') {
cout << "[-Y]补: " << Y << endl;
} else {
cout << "[Y]补: " << Y << endl;
}
int flag = 0; // 标记是否要进位
for (int i = X.length() - 1; i >= 0; i--) {
int cur = X[i] - '0' + Y[i] - '0' + flag;
if (cur > 1) {
flag = 1;
} else {
flag = 0;
}
if (cur & 1) {
X[i] = '1';
} else {
X[i] = '0';
}
}
printf("------------------\n");
cout << "[X" << oper << "Y]补: " << X << endl;
cout << " X" << oper << "Y : " << B2Y(X) << endl;
checkOverFlow(X);
return X;
}
int main() {
system("chcp 65001");
cin.tie(0);
cout.tie(0);
// bitset<7> a(27);
// string strX = a.to_string();
Cal("0011011", "0000011");
Cal("0011011", "1110101");
Cal("0011011", "1110011", '-');
return 0;
}
nt布置你马的那么多题目…
发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/179210.html原文链接:https://javaforall.cn