Hi all, I am currently trying to generate a number from a specified range
using a function

int number_range(int from, int to) {
    return (from + rand() % (to-from+1));
}

but negative numbers cause the program to crash.
How can i go about doing this so it can take numbers of all kinds?

Recommended Answers

All 4 Replies

It can make problem if from > to. Check it.

Else try this.

ans = to - from ;

flag = rand() % ans + 1 ;

return (from + ans) ;

You can use the abs function from the math.h header file to get the aboslute value of the generated random number and then operate as necessary.

The correct form is:

(rand() % (max-min+1) + min;

Refer to my die's application and u solve ur issue youself:

#include <iostream>
#include <math.h>
#include <cstdlib>
#include <ctime>
using namespace std;

int main()
{
  int any,any2;

  cout<<"Enter a random number  : ";
  cin>>any;

     srand(time(0));
     any2=1+(rand()%6);
    cout <<"The random number is : "<<any2 << endl;
    if(any==any2){
    //your oode
    }
    else {//your oode
    }
}
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.