我正在用C++編寫一個簡單的應用程序,用來計算總和的頻率(即當你擲骰子時)。程序完全運行,它甚至產生了正確的結果,但是在執行結束時,Windows告訴我程序停止工作。C++程序完全執行,但最終破壞?
我正在使用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;
}
警告:您正在使用可變長度數組('val [n]'和'frq [t]')。這些是非標準的語法,容易導致堆棧溢出。 – user4581301
另請注意:使用字母表變量命名方案對試圖調試代碼的人來說是一種抑制措施。一路平安。 – user4581301