Sum up and Average

Hi guys, I am just a beginners at C++ and I wrote this small code and I am trying to sum up the numbers and average them, but I am not sure what to do, when I use sum += x, it gives me weird number. So could you guys help me please. Thanks in Advance.

#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;


int main ()
{

int start,x;
cout << "Enter the number of time u would like to roll " << endl;
cin >> start;

srand (time(0));

for (x=1; x <= start; x++) {
cout << 1+ rand()%6 << endl;
}


system ("pause");
return 0;
}
Well, the code you posted doesn't demonstrate the problem you are asking about. I don't see any variable named sum here.

But there are a few possibilities. First make sure that sum is set to zero at the start. In your sample code, x is the loop counter, if you did sum += x, that would give the total of the integers from 1 to start.

I'd say, rather than simply putting cout << 1+ rand()%6 << endl;,
first save the random number in a separate variable, which you could then use both for display, and for other calculations.
1
2
    int num = 1 + rand()%6; 
    cout << num << endl;
Last edited on
Thank you very much. It actually did help. However, I am not sure why but it doesn't generate random numbers, it just repeats the same number over and over until loops ends. Could u please help me, thanks again.

#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;


int main ()
{

int start,x,sum;
cout << "Enter the number of time u would like to roll " << endl;
cin >> start;
srand (time(0));
int number = rand()%6 + 1;




for (x=1; x <= start; x++) {
cout << number << endl;
sum += number;
}

cout << sum;


system ("pause");
return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;

int main ()
{
    int start,x,sum;
    cout << "Enter the number of time u would like to roll " << endl;
    cin >> start;
    srand (time(0));
    for (x=1; x <= start; x++) 
    {
        int number = rand()%6 + 1;//<<<<<<<
        cout << number << endl;
        sum += number;
    }
    cout << sum;
    system ("pause");
    return 0;
}
Topic archived. No new replies allowed.