-
logic Error
with this program i am supposed to use a vector to store the numbers of times each possible sum of the two dice appears. I am rolling the dice 36000 times. The vector contains 11 element from 2 to 12. could you tell me why i am not getting reasonable results. i am getting a very huge number for case 12..
Code:
#include<iostream>
using namespace std;
#include<vector>
using std::vector;
#include<cstdlib>
using std::rand;
using std::srand;
#include<ctime>
using std::time;
#include<iomanip>
using std::setw;
int SumOfDice;
vector<int>Frequency(11);
int x;
int y;
int main()
{
int sumOfDice;
vector<int>Frequency(11);
int x;
int y;
srand(time(0));
for( int i=1; i<=36000; i ++)
{
x = 1+rand()%6;
y =1 +rand()%6;
SumOfDice = x+y;
switch (SumOfDice)
{
case 2:
Frequency[SumOfDice]++;
break;
case 3:
Frequency[SumOfDice]++;
break;
case 4:
Frequency[SumOfDice]++;
break;
case 5:
Frequency[SumOfDice]++;
break;
case 6:
Frequency[SumOfDice]++;
break;
case 7:
Frequency[SumOfDice]++;
break;
case 8:
Frequency[SumOfDice]++;
break;
case 9:
Frequency[SumOfDice]++;
break;
case 10:
Frequency[SumOfDice]++;
break;
case 11:
Frequency[SumOfDice]++;
break;
case 12:
Frequency[SumOfDice]++;
break;
default :
cout<<"incorrect number"<<endl;
break;
}
}
cout<<"Frequency"<<setw(50)<<"number of times each sum appears"<<endl;
for( int i = 2;i<=12;i++)
cout<<i<<setw(50)<<Frequency[i]<<endl;
return 0;
}
//the output is
Frequency number of times each sum appears
2 1017
3 2024
4 2939
5 4104
6 5023
7 6066
8 4993
9 3855
10 3020
11 1993
12 134523750
-
You're reading (and writing) beyond the end of the vector. You allocated a vector of size 11. That's Frequency[0] - Frequency[10], but you're using Frequency[2] - Frequency[12].
-
EDIT: opps, beat me to....gee, my internet connection isn't that slow, surely :eek:
As it is, it *looks* like your display function is trying to call beyond what it exists, thus the large reading. Change your vector to 13, should fix that ?
-
Code:
int SumOfDice;
vector<int>Frequency(11);
int x;
int y;
int main()
{
int sumOfDice;
However descriptive, naming variables where the only difference is caps can lead to unnecessary bugs and dificulty reading.
-
Code:
x = 1+rand()%6;
y =1 +rand()%6;
SumOfDice = x+y;
=?
Code:
x = rand()%6;
y = rand()%6;
SumOfDice = x+y+2;