这个代码有几个问题:
1. 对于负数的处理不正确。在计算机中,负数的二进制表示通常使用的是二进制补码,即首先取其绝对值的二进制表示,然后对每一位取反(0变为1,1变为0),最后加1。但在你的代码中,你只是简单地对每一位取反,没有加1。
2. 对于0的处理不正确。在你的代码中,你试图输出32个0,但是你使用的是整数000000000000000000000000000000,这在C++中会被解析为一个整数0,而不是一个包含32个0的字符串。你应该使用字符串\"00000000000000000000000000000000\"。
3. 对于二进制数的长度处理不正确。在你的代码中,你试图通过添加前导0来使二进制数的长度达到32位,但是你没有考虑到当输入的整数已经是32位时,你的代码会产生一个长度超过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;
- cin >> n;
- string res;
- string x = "0";
- vector<int> shuzi;
- int n2 = n;
- if (n2 < 0)
- {
- n = -n;
- }
- do
- {
- shuzi.push_back(n % 2);
- n = n / 2;
- } while (n != 0);
- int len = shuzi.size();
- res = cheng(x, 32 - len);
- for (int i = shuzi.size() - 1; i >= 0; i--)
- {
- res = res + to_string(shuzi[ i]);
- }
- if (n2 < 0)
- {
- for (int i = 0; i < 32; i++)
- {
- res[ i] = res[ i] == '1' ? '0' : '1';
- }
- for (int i = 31; i >= 0; i--)
- {
- if (res[ i] == '1')
- {
- res[ i] = '0';
- }
- else
- {
- res[ i] = '1';
- break;
- }
- }
- }
- cout << res;
- return 0;
- }
复制代码
这个修正后的代码首先将输入的整数转换为二进制表示,然后如果输入的整数是负数,就对二进制表示进行取反和加1操作,得到二进制补码。
请注意,本回答来自GPT-4
如果问题已经解决,请设置最佳答案