簡體   English   中英

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:\tINVALID\nDesc:\t";
        if(cin.good() && (input <= lower || input >= upper))
            cout << "OUT OF BOUNDS [" << lower << " <= val <= " << upper << "]";    
        else
            cout << "NAN";  
        cout << "\n\n";
        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遠遠超過val[]的大小n ,從而在數組末尾寫入零。 那是災難性的。 您需要做while(pos < n && val[pos] >= r){...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM