Yahoo Clever wird am 4. Mai 2021 (Eastern Time, Zeitzone US-Ostküste) eingestellt. Ab dem 20. April 2021 (Eastern Time) ist die Website von Yahoo Clever nur noch im reinen Lesemodus verfügbar. Andere Yahoo Produkte oder Dienste oder Ihr Yahoo Account sind von diesen Änderungen nicht betroffen. Auf dieser Hilfeseite finden Sie weitere Informationen zur Einstellung von Yahoo Clever und dazu, wie Sie Ihre Daten herunterladen.
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 Antworten
- vor 1 JahrzehntBeste Antwort
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 7vor 1 Jahrzehnt
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).
- Wie finden Sie die Antworten? Melden Sie sich an, um über die Antwort abzustimmen.
- tbshmkrLv 7vor 1 Jahrzehnt
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 4vor 1 Jahrzehnt
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 :)