hey all

i want to write a program to generate a random number from 0 to 100
but i don't know how to make the number be between 0 and 100 only

another thing that when i write the following code the computer always choose the same random number which is "41"

#include<iostream>
#include<stdlib.h>
using namespace std;
void main(){
	int n;
	
		n=rand();
		cout<<n<<endl;

}
}

could any body help me with these two problems??

my salute to all

>#include<stdlib.h>
To be strictly correct, this should be <cstdlib>.

>void main(){
main returns int.

>i don't know how to make the number be between 0 and 100 only rand() % 100 is the easiest way, and it should suffice for basic pseudorandom numbers.

>the computer always choose the same random number which is "41"
You have to seed the generator with the srand function if you want the sequence to change between runs of the program.

>
>i don't know how to make the number be between 0 and 100 only rand() % 100 is the easiest way, and it should suffice for basic pseudorandom numbers.

I believed, rand() % 101 would generate number between 0 and 100

>I believed, rand() % 101 would generate number between 0 and 100
So it would. Shame on me for rushing.

rand() function just generates random number. it is us who have to decide the range in which we want the random number to be...
and taking mod is the easiest way to confine it...
general form is ... rand()%range;

Narue is correct...
you will have to use srand function to randomize the randome number generation...which takes an unsigned integer number as a seed....but take care of one thing....if you use srand function with same seed every time you run the program then again it will generate the same number....

solution to this is to use system clock as the seed...time keeps changing so is your seed...so is the random number

hey all

i want to write a program to generate a random number from 0 to 100
but i don't know how to make the number be between 0 and 100 only

another thing that when i write the following code the computer always choose the same random number which is "41"

#include<iostream>
#include<stdlib.h>
using namespace std;
void main(){
	int n;
	
		n=rand();
		cout<<n<<endl;

}
}

could any body help me with these two problems??

my salute to all

Here is the solution:

#include <iostream>
#include <stdlib.h>
#include <time.h>
using namespace std;
void main(){
	int n;
            srand((unsigned int)time());
            n=rand()%101;
	cout<<n<<endl;

}
}

Happy New Year!

zhelih needs to read post #2 as well.
Like the bit on how to declare main, and the correct name for header files.

Here is the solution:

Happy New Year!

dont throw solutions...directly

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.