[英]How the assigned value to variable gets changed automatically?
When I am providing input for std::cin >> diff;
当我为
std::cin >> diff;
提供输入时std::cin >> diff;
it takes the input value, and the moment I am entering the value of array, the diff variables value gets changed and sets the value of 4th element
of the array. 它取输入值,当我输入数组的值时,diff变量值被改变并设置数组的
4th element
的值。 Please help me where is it going wrong. 请帮帮我哪里出错了。 I have tried with
fflush(std)
. 我试过用
fflush(std)
。 But it did not help me. 但它没有帮助我。
I am using Visual Studio 2010 Ultimate edition
. 我正在使用
Visual Studio 2010 Ultimate edition
。
#include "stdafx.h"
#include <stdio.h>
#include <iostream>
#include <stdlib.h>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
int i, num;//[]={0};
int diff = 0;
int numset[] = {0};
int temp, cnt;
cnt = num = i = 0;
std::cout << "Enter your number and difference : ";
//fflush(stdin);
std::cin >> num ;
std::cin >> diff;
cout << "Enter array Elements : \n";
for(i = 0; i < num; i++)
{
cin >> numset[i];
//fflush(stdin);
}
for(i = 0; i < num; i++)
{
for(int j = i; j < num; j++)
{
if(i == j)
{
temp = numset[j];
}
else
{
if((diff == (numset[j] - temp)) || (((-1)*diff) == (numset[j] - temp)))
{
cnt++;
}
}
}
}
cout << cnt << endl;
system("pause");
return 0;
}
You're accessing beyond the bounds of the array numset
, so your code has Undefined Behaviour (UB) and anything could happen. 您正在访问超出数组
numset
的边界,因此您的代码具有未定义的行为(UB),并且可能发生任何事情。 It could overwrite variables on stack (as it does in your case), it could crash, it could order pizza online. 它可以覆盖堆栈上的变量(就像你的情况一样),它可能会崩溃,它可以在线订购披萨。
numset
is declared as a single-element array, so accessing numset[i]
for i > 0
results in UB. numset
被声明为单元素数组,因此为i > 0
访问numset[i]
产生UB。 You should probably change numset
to be a std::vector<int>
and use push_back()
to append numbers to it. 您应该将
numset
更改为std::vector<int>
并使用push_back()
向其追加数字。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.