数组显示比平常更多的结果

teo*_*o93 2 c++ arrays binary decimal

这是我的代码:

#include <iostream>
using namespace std;

int main()
{
  char character;
  int x;
  cout << "Input a character: " ;
  cin >> character;
  x = int(character);
  cout << "Its integer value is: " << x << endl;
  int arr[7], i=0,j;
  while(x>0)
  {
    arr[i]=x%2;
    i++;
    x=x/2;
  }
  cout << "Its Binary format is: ";
  for (j=i; j>=0;j--)
  {
    cout<<arr[j];
  }
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

我只为此代码分配了8个数组空间,但显示的结果大于8,与算法完全无关.我怀疑这是一个溢出问题.我该如何解决这个问题?谢谢!

gio*_*gim 5

while(x>0)
{
    arr[i]=x%2;
    i++;
    x=x/2;
}
Run Code Online (Sandbox Code Playgroud)

让我们来看看这个循环执行一次的情况. i循环结束后为1.但是,索引1处的数组元素未初始化.

您尝试在此处打印时触发未定义的行为:

for (j=i; j>=0;j--) // assuming for should be here
{
    cout<<arr[j]; // access array element with index 1 (our example)
}
Run Code Online (Sandbox Code Playgroud)

修复是将您的循环更改为

for (j=i-1; j>=0;j--)
Run Code Online (Sandbox Code Playgroud)

还要注意用户输入的数字是否大于(或等于)2的7次幂.数组中没有地方存储所有数字.并且将通过尝试写入数组的末尾来再次触发未定义的行为.