问题描述:
这段代码用于求一个32位整数的二进制补码,但是运行时出现错误。请问问题出在哪里?#include <iostream>using namespace std;#include <string>#include <vector>string cheng(string x, int n){ string res = ""; for (int i = 1; i <= n; i++) { res = res + x; } return res;}int main(){ int n; int len; cin >> n; string res; string x = "0"; vector<int> shuzi; int n2 = n; if (n2 < 0) { n = 1-n; } while (n != 1) { shuzi.push_back(n % 2); n = n / 2; if (n == 1) { shuzi.push_back(1); } } len = shuzi.size(); if (n2 > 0) { res = cheng(x, 32 - len); for (int i = shuzi.size() - 1; i >= 0; i--) { res = res + to_string(shuzi[i]); } cout << res; return 0; } else if (n2 == 0) { cout << 000000000000000000000000000000; return 0; } else { res = cheng(x, 32 - len); for (int i = shuzi.size() - 1; i >= 0; i--) { res = res + to_string(shuzi[i]); } for (int i = 0; i <= 32; i++) { if (res[i] == '1') { res[i] = '0'; } else { res[i] = '1'; } } cout << res; return 0; }}
解决方案:
这段代码存在几个问题导致运行时出现错误:
1. 在使用using namespace std;时,应该将其放在头文件的外部,而不是在iostream头文件之后。例如,将using namespace std;移动到#include <string>之前。
2. 当输入为0时,输出的补码应该是全0而不是十进制的0。在输出0的补码时,需要将cout << 000000000000000000000000000000;修改为cout << "000000000000000000000000000000";,将其作为字符串进行输出。
3. 在对补码进行取反时,需要注意循环的结束条件。当前的代码中,循环条件为i <= 32,但数组的索引范围是0到31,所以应该修改为i < 32。
下面是修改后的代码:#include <iostream>#include <string>#include <vector>using namespace std;string cheng(string x, int n){ string res = ""; for (int i = 1; i <= n; i++) { res = res + x; } return res;}int main(){ int n; int len; cin >> n; string res; string x = "0"; vector<int> shuzi; int n2 = n; if (n2 < 0) { n = 1 - n; } while (n != 1) { shuzi.push_back(n % 2); n = n / 2; if (n == 1) { shuzi.push_back(1); } } len = shuzi.size(); if (n2 > 0) { res = cheng(x, 32 - len); for (int i = shuzi.size() - 1; i >= 0; i--) { res = res + to_string(shuzi[i]); } cout << res; return 0; } else if (n2 == 0) { cout << "000000000000000000000000000000"; return 0; } else { res = cheng(x, 32 - len); for (int i = shuzi.size() - 1; i >= 0; i--) { res = res + to_string(shuzi[i]); } for (int i = 0; i < 32; i++) { if (res[i] == '1') { res[i] = '0'; } else { res[i] = '1'; } } cout << res; return 0; }}
请注意,以上修改只是修复了代码中的错误,并不保证逻辑的正确性。对于负数的二进制补码表示,可能需要考虑符号位的处理。具体实现还需根据需求进行调整。
球一个最佳答案谢谢啦!这对我非常重要! |