### Random number generator with range don't work.

#include "stdafx.h"
#include <iostream> //to use cout and cin and endl// allows using cout without std::cout
#include <string> // to use string data type
#include <cstring> //to use strlen, strcmp, strcpy
#include <cmath> //for pow function,sqrt,abs
#include <iomanip> // for set precision, setw,
#include <fstream> //for file input
#include <cassert> // to use assert to disable place before #define NDEBUG
#include <cstdlib>//for random numbers, exit function
#include <ctime>//time function used for rand seed
#include <cctype> // for toupper, tolower
using namespace std;
using namespace System;

int main()
{
int randScore = 0;
srand(time(0));
for (int j = 0; j < 3; j++)
{
randScore = (rand () % 100) + 60;
cout<< randScore << endl;
}

system("PAUSE");
return 0;
}

the above code needs to return random number between 60 and 100. but it returns number over 100. any help will be appreciated. Thanks in advance!!
Last edited on
rand() produces a random number
% performs a modulus operation (ie: gives you the remainder after addition)
I don't think I need to explain what + does

`rand() % 100` will give you a number between [0..99] because any number divided by 100 is going to have a remainder of less than 100.

So if you have a range of [0..99] and you add 60 to it, that changes your range to [60..159], making it possible to have results over 100.

With that in mind... the typical way to do range-restricted random number generation is with `(rand() % range) + minimum`. If you want a range of [60..100), that would be range=40, minimum=60
Great. That worked. I thought the number after "%" was max value and the number after "+" was minimum value. But now it's clear. Thanks so much !!
Topic archived. No new replies allowed.