如何自动更改变量的赋值
How the assigned value to variable gets changed automatically?
当我为std::cin >> diff;
提供输入时,它取输入值,当我输入数组的值时,diff变量的值会发生变化,并设置数组的4th element
的值。请帮我哪里出了问题。我试过fflush(std)
。但这对我没有帮助。
我正在使用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;
}
您的访问超出了数组numset
的范围,因此您的代码具有未定义行为(UB),任何事情都可能发生。它可能会覆盖堆栈上的变量(就像在您的情况下一样),可能会崩溃,可能会在线订购披萨。
numset
被声明为单个元素数组,因此对i > 0
访问numset[i]
会导致UB。您可能应该将numset
更改为std::vector<int>
,并使用push_back()
向其添加数字。
相关文章:
- 为"adjacent"变量赋值时出现问题
- 非常量变量只读位置的赋值
- 变量在使用赋值语句赋值后恢复为以前的值
- 为什么我不能在返回 const 的布尔函数中为类成员变量赋值?C++
- 如何在 c++ 中正确声明/赋值变量的值
- 在未初始化的变量上使用复合赋值运算符(+=, ..)不是C++中的UB?
- c++问题:给一个变量赋值后,另一个变量发生了变化
- 如何在不使用赋值运算符的情况下为动态变量赋值?
- 为什么我不能为变量赋值函数?
- 可视化的c++变量赋值使代码正常工作
- 作为赋值(增加引用变量)C++的左操作数所需的左值
- 如何为结构类型变量赋值
- const变量是否可以在具有默认值的参数中赋值(作为可选参数)
- C++中重载复合赋值运算符不会更改变量
- 初始值设定项列表与构造函数赋值与变量定义
- 在结构的构造函数中使用类方法赋值变量
- 原子变量的多重赋值是原子操作吗?
- 在 If 语句 [C++] 中赋值变量
- 赋值变量时c++未处理异常访问冲突
- 使用reinterpret_cast赋值变量后可能的析构函数