c++程序完全执行,但在结束时中断
C++ Program executes completely, but breaks at the end?
我正在用c++编写一个简单的应用程序,旨在计算总和的频率(即当你掷骰子时)。程序完全运行,它甚至产生了正确的结果,但是在它执行的最后,Windows告诉我程序停止工作了。
我使用Dev-Cpp 5.11和TDM-GCC 4.9.2 32位版本编译器来创建和编译下面的代码。
#include<iostream>
#include<limits>
#include<string>
using namespace std;
const int int_min = numeric_limits<int>::min(),
int_max = numeric_limits<int>::max();
int getint(string ln, int lower, int upper){
int input = 0;
cout << ln;
if(cin >> input && input >= lower && input <= upper){
cin.clear();
cin.ignore(80,'n');
}else{
cout << "ERR:tINVALIDnDesc:t";
if(cin.good() && (input <= lower || input >= upper))
cout << "OUT OF BOUNDS [" << lower << " <= val <= " << upper << "]";
else
cout << "NAN";
cout << "nn";
cin.clear();
cin.ignore(80,'n');
return getint(ln,lower,upper);
}
return input;
}
int main(){
int
n = getint("Input(n) > ",1,int_max),
a = getint("Input(a) > ",0,int_max),
b = getint("Input(b) > ",a,int_max),
r = b - a + 1,
t = n * (r - 1) + 1;
int
pos = 0,
sum = 0,
val[n],
frq[t];
for(int i = 0; i < n; i++)
val[i] = 0;
for(int i = 0; i < t; i++)
frq[i] = 0;
while(pos < n){
pos = 0;
sum = 0;
for(int i = 0; i < n; i++)
sum += val[i];
frq[sum]++;
val[pos]++;
while(val[pos] >= r){
val[pos++] = 0;
if(pos <= n - 1)
val[pos]++;
}
}
for(int i = 0; i < t; i++){
cout << "frq(" << i + n << ")t|t" << frq[i] << endl;
}
return 0;
}
循环while(val[pos] >= r){...
可以继续循环,直到pos
远远超过n
,这是val[]
的大小,因此在数组末尾之后写入零。这是灾难性的。你需要输入while(pos < n && val[pos] >= r){...
相关文章:
- 为什么在这个代码结束循环中没有得到结束
- 试图对缓存进行跨步测试,但程序并没有结束
- 当调用switch语句中的函数时(即使函数不包含循环),似乎是永不结束的循环的问题
- 为什么擦除方法会影响结束方法
- 根据用户输入用字母填充矢量,并将"开始"和"结束"放在四肢
- 类成员和中断
- 删除映射和分割错误中的一个过去结束元素
- 捕获标准输出以压缩并使用 CTRL-C 中断会给出损坏的 zip 文件
- 我的代码运行良好,但在游戏循环中中断
- 如何使用 SFML 在贪吃蛇游戏中定义游戏结束?
- 使用带有MCP23017的 pigpio 进行中断读取
- 为什么我的两个 cin 语句没有在程序结束时运行?
- 为什么我在 AVR 中的中断无法正常工作?
- 在函数结束后使用指向变量的指针是否安全?
- C ++尝试并捕获未结束的程序
- 为什么我的程序在输入某个形状的面积的测量值后没有结束?
- 取消引用结束指针到数组类型的一个
- 如何在 c++ 中确定一条指令(以字节为单位)在哪里结束,另一条指令从哪里开始?
- 使用 shared_ptr 在中断时结束多线程循环
- c++程序完全执行,但在结束时中断