i tried the following coding .it compiled without errors but gave absurd results during runtime. can u pls help me with it?
#include
#include
int main()
{
int i;
cout<<"ten random numbers for the range 0 to 50"<
You probably want the "return 0" AFTER the for-loop is over. When it hits that, it'll just end the program. Moving that line so that it was AFTER the for-loop gave me these results:
ten random numbers for the range 0 to 50
41
18467
6334
26500
19169
15724
11478
29358
26962
24464
Note that you are not seeding the random number generator with the srand function, so don't be surprised if you get the same numbers every time.
VernonDozier
Posting Expert
5,527 posts since Jan 2008
Reputation Points: 2,633
Solved Threads: 711
Well i have seen your code. It actually can create random numbers from the whole integer set.
Therefore i have just edited the whole program and made it such that it will get random numbers from 0 to 50.
Please dont copy the code but, Check out how the loop actually is running and implement it on your own.
#include<iostream>
using namespace std;
int randomnumber();
int main()
{
int i;
cout<<"ten random numbers for the range 0 to 50"<<endl;
for(i=0;i<10;i++)
{
randomnumber();
}
cin.get();
}
int randomnumber()
{
int j;
j = rand();
if (!(j >= 50))
{
if (!(j<=0))
{
cout<< j<<"\n";
}
}
else {randomnumber();}
}
Hope your problem is solved with this.
However there is another problem . Some times the random numbers may be the same. I mean there can be two 28 or any other number coming out. Try avoiding it by using an array.
Sky Diploma
Practically a Posting Shark
865 posts since Mar 2008
Reputation Points: 673
Solved Threads: 131
Consider using the % operator.
Recursion in this instance is very poor, because there is no clear exit condition and it may take a very long time (and thus a large amount of stack - perhaps too much) before you get the result you want.
Salem
Posting Sage
11,531 posts since Dec 2005
Reputation Points: 5,862
Solved Threads: 953
So instead of Recursion i should go on getting the remainder by dividing the number with some value like 50 or so?
Sky Diploma
Practically a Posting Shark
865 posts since Mar 2008
Reputation Points: 673
Solved Threads: 131
Apropos, I far as I know, rand() % N (where rand() is a pseudo-random numbers generator) is NOT uniformely distributed in 0..N-1 range...
Right (but cumbersom) construct is (alas):
(int)(N*(rand()/(double)MAX_RAND))
ArkM
Postaholic
2,001 posts since Jul 2008
Reputation Points: 1,234
Solved Threads: 348