Help please. I need to generate 200 number in a file. Each of these 200 numbers is the sum of 12 random number from 0-8 using rand()%9. But every time it goes through the while loop it generates the same number it generated for the first time. I've tried srand(time(NULL)) and it doesn't work. I placed it in different location of the code and it didn't help either. What do I need to do?

****************************************************************************** #include <iomanip>

#include <iostream>

#include <fstream>

#include <cstdlib>

#include <stdlib.h>

#include <ctime>

using namespace std;

int main()

{

int counter = 0;

int counter12 = 0;

int sum = 0;

//OPEN THE FILE

ofstream rData;

rData.open ("random.txt");

srand((unsigned)time(0));

//WRITE TO A FILE, START COUNTING 200 TIMES

while(counter < 200)

{

//START COUNTING 12 times to add up the sum

while(counter12 < 12)

{

sum += (rand()%9);

counter12++;

}

//INSERT THE SUM INTO A FILE

rData << sum << ' ' ;

counter++;

}

rData.close();

return 0;

}

**************************************************************************

****************************************************************************** #include <iomanip>

#include <iostream>

#include <fstream>

#include <cstdlib>

#include <stdlib.h>

#include <ctime>

using namespace std;

int main()

{

int counter = 0;

int counter12 = 0;

int sum = 0;

//OPEN THE FILE

ofstream rData;

rData.open ("random.txt");

srand((unsigned)time(0));

//WRITE TO A FILE, START COUNTING 200 TIMES

while(counter < 200)

{

//START COUNTING 12 times to add up the sum

while(counter12 < 12)

{

sum += (rand()%9);

counter12++;

}

//INSERT THE SUM INTO A FILE

rData << sum << ' ' ;

counter++;

}

rData.close();

return 0;

}

**************************************************************************

//WRITE TO A FILE, START COUNTING 200 TIMES

while(counter < 200)

{

**sum = 0;**

counter12 = 0;

//START COUNTING 12 times to add up the sum

while(counter12 < 12)

{

sum += (rand()%9);

counter12++;

}

while(counter < 200)

{

counter12 = 0;

//START COUNTING 12 times to add up the sum

while(counter12 < 12)

{

sum += (rand()%9);

counter12++;

}

Thank you Vlad! Now I see that counter12 and sum didn't come to zero again to calculate another number! Thanks a lot!

Topic archived. No new replies allowed.