c++程序完全执行,但在结束时中断

C++ Program executes completely, but breaks at the end?

本文关键字:结束 中断 程序 执行 c++      更新时间:2023-10-16

我正在用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){...