Member Avatar for Jackk123

Soo last year, if im not mistaken , i asked for help with the random numbers generator.
I didn't do C++ for quite some time, but i started again.
So here is what i have :

#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <ctime>
using namespace std;

int main(){
	srand(time(NULL));
	int random;
	ofstream outfile("C:\\Random.txt"); //Random as in you can put any file you want
	if (outfile.is_open())
        {
                for (int i = 0; i < 10; i++)
                {
					random=(rand()%100);
					outfile << i << ": " << random <<endl;
                }
	     }
        outfile.close();
        return 0;
}

The code is supposed to write 10 random numbers to a file. I know its noot good after the "for" part
because for now it only generates from 0-100.
Can someone help me with this code?
It supposed to generate random numbers between 0 and 32000 (not sure how much rand exactly is ) its somewhere around 32000-33000 i think i forgot it.

Tnx

I think you can do that:
random=3200*(rand()%100);

is this helpful or not?

As is explained here, the maximum value for rand() (defined as RAND_MAX ) is implementation defined, but is at least 32767 for a compliant compiler and library.

As for how to get the specific range you want, you need to use a combination of modulo ( % ) and addition or subtraction. So, for a range of (say) 32,000 to 33,000, you would want a range size of 1000 and an offset of 32,000:

random = (rand() % 1000) + 32000;

Different ranges and offset can be easily selected from this basic pattern.

Member Avatar for Jackk123

Thanks for answering
but what i want is

for it to generate from 0-32767
which is defined RAND_MAX , i couldn't get that to work.
I know how the range works.

rand()%RAND_MAX should generate [0,32767) meaning the number will never be 32767.

If you want it to include 32767 then just use rand()%(RAND_MAX+1).

Member Avatar for Jackk123

So i put random=rand()%RAND_MAX or?

Yeah if you want it to include 0 and be one less than RAND_MAX for your range.

Member Avatar for Jackk123

it works now , tnx

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.