Yahoo Answers is shutting down on May 4th, 2021 (Eastern Time) and beginning April 20th, 2021 (Eastern Time) the Yahoo Answers website will be in read-only mode. There will be no changes to other Yahoo properties or services, or your Yahoo account. You can find more information about the Yahoo Answers shutdown and how to download your data on this help page.
Trending News
can you set limits on the rand() function in C/C++?
basically i need to come up with random numbers but within a specific range. is there away to do that with rand() or do i have to write my own algorithm to do this?
6 Answers
- 1 decade agoFavorite Answer
Numbers in a specific range can be obtained by the modulo operator (%). For example, let's say we want an integer from 0 to 9. Here would be the code:
int randnumber = rand() % 10;
% returns the remainder when the two numbers are divided. So in this case, it could return anywhere from 0 to 9, because those are the valid remainders. If we want a number from 1 to 10, we do this:
int randnumber = rand() % 10 + 1;
If you want a random float between 0 and 1, do this (RAND_MAX is the highest possible value that rand() can return):
float randnumber = (float) rand() / (float) RAND_MAX;
- RatchetrLv 71 decade ago
You use the mod operator...% to set the upper limit.
You use + to set the lower limit.
rand() % x will give you numbers between 0 and x-1.
rand() % x + n will give you numbers in the range n to n +(x-1).
- How do you think about the answers? You can sign in to vote the answer.
- tbshmkrLv 71 decade ago
Try this code == 20 PseudoRandom Integers 5000 to 6000
=
#include <iostream>
#include <iomanip>
#include <ctime>
#include <cstdlib>
using namespace std;
int main()
{
srand((unsigned)time(0));
int random_integer;
int lowest = 5000;
int highest = 6000;
int range;
range = (highest - lowest) + 1;
for(int index = 0; index < 20; index++)
{
random_integer = lowest + int(range * rand()/(RAND_MAX + 1.0));
cout << setw(3) << index << " " << setw(3) << random_integer << endl;
}
return 0;
}
- newfaldonLv 41 decade ago
If you want a random number between A & B then you need to do rand()*(B-A)+A. Of course, you might need to do some type casting depending on A, B, and what you want to return.
This website offers another way.. probably more elegant than mine :)