Strange Problem

I'm in a c++ programming class, and I have an assignment a dice game.

Here's the code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include <cstdlib> 
#include <iostream>
#include "math.h"

using namespace std;

void dice(int numOfSide, int numOfRolls)
{
int rndNum, counter=0, total, lastNum, avgNum, lastScores;
int scores[numOfRolls]; // OMG it's an array of scores
do {
	srand( (unsigned)time( NULL ) );
	rndNum = (rand() % numOfSide) + 1;
	cout << rndNum + "\n";
	scores[counter] = rndNum;
	//totaling is fun
	lcastNum = scores[counter];
	if(counter!=1)
	{
		total = lastNum + scores[counter];
	}
	//done with fun totaling
	++counter;
}while(counter != numOfRolls);
/* Time to process the scores */
avgNum = total/numOfRolls;
cout << "Your total is " << total << "\n";
cout << "Your average is "<< avgNum << "\n";
getchar();
}

int main()
{
int rolls, sides;
cout << "How many rolls? ";
cin >> rolls;
cout << "How many sides? ";
cin >> sides;
dice(sides, rolls);
}

Here's the output:
1
2
3
4
How many rolls? 6
How many sides? 6
r total is r total is r total is r total is r total is r total is Your total is 10
Your average is 1


I don't understand why it says "r total is" 7 times. There's no loop there. I asked my friend and my teacher and they didn't know why either.
How does that even compile? Arrays can only be declared by constant variables. There are so many errors in that code that it would never compile.

Line 14:
cout << rndNum + "\n"; // Not an error, just impractical
should be
cout << rndNum << "\n";

Line 17:
lcastNum = scores[counter];
should be
lastNum = scores[counter];

Last edited on
1) this code doesn't compile. You can't make declare 'scores' the way you are on line 10. If you want to have a variable size, either use std::vector, or allocate it with new:

1
2
3
4
int* scores = new int[numOfRolls];

// then at end of function
delete[] scores;


also I assume line 17 is supposed to be 'lastNum' and not 'lcastNum'.

2) you're using time(), but not including <ctime>

3) don't srand repeatedly. It defeats the point of using it. You're only supposed to do it once at startup, not for every random number. Move the srand call to main

4) (your actual problem) Look at line 14. You're adding a pointer to an integer, and then couting the result. This results in a pointer offset by 'rndNum' which is a bad pointer, which makes cout output garbage.

Do not use the + operator like this. Instead change that line to:

cout << rndNum << "\n";

edit -- bah I'm too slow ;_;
Last edited on
Topic archived. No new replies allowed.