[英]array displaying more results than normal
this is my code: 这是我的代码:
#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;
}
I have only 8 array spaces allocated for this code but the displayed result is more than 8 and is totally unrelated to the algorithm. 我仅为此代码分配了8个数组空间,但是显示的结果超过8个,并且与算法完全无关。 I'm suspecting this to be an overflow issue. 我怀疑这是一个溢出问题。 How do i remedy this issue? 我该如何解决这个问题? Thank you! 谢谢!
while(x>0)
{
arr[i]=x%2;
i++;
x=x/2;
}
let's take case when this loop is executed once. 让我们以这个循环执行一次为例。 i
is 1 after loop is finished. 循环结束后i
为1。 However, array element at index 1 is not initialized. 但是,索引1处的数组元素未初始化。
You trigger undefined behaviour by trying to print it here: 您可以通过尝试在此处打印未定义的行为来触发它:
for (j=i; j>=0;j--) // assuming for should be here
{
cout<<arr[j]; // access array element with index 1 (our example)
}
The fix is to change your loop to 解决方法是将循环更改为
for (j=i-1; j>=0;j--)
Also beware what if user enters number which is larger (or equal) than 7th power of 2. You won't have places in your array to store all digits. 同样要注意,如果用户输入的数字大于(或等于)2的7的次幂,该怎么办?您的数组中将没有位置存储所有数字。 And will trigger again undefined behaviour, by trying to write past the end of the array. 并尝试通过在数组末尾进行写操作来再次触发未定义的行为。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.