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?

Dani AI

Generated

The crash you see is not because rand() cannot handle negative numbers — it is caused by undefined/incorrect arithmetic around the range. If (to - from + 1) becomes zero, negative, or overflows a signed int, the right-hand operand to % is invalid and you get UB (or a crash). was right to check the ordering; 's abs idea does not address ordering or overflow; 's compact formula only works when min <= max and the subtraction does not overflow; showed seeding, but seeding should happen once at program startup (not inside each call).

A safer approach:

  • Validate or swap inputs so min <= max.
  • Compute the range in an unsigned 64-bit type to avoid signed overflow.
  • Use rejection sampling rather than a single rand() % range to avoid bias and to ensure the modulus operand is positive.
  • Build a wide-enough random candidate by combining rand() calls (portable) or use a platform API like arc4random_uniform / random() / C++11 <random> when available.
  • Seed the RNG once at program start (srand(time(NULL))) if using rand().

Example (portable C, avoids overflow and reduces bias):

#include <stdlib.h>
#include <limits.h>
#include <stdint.h>

int number_range_safe(int a, int b) {
    int min = a, max = b;
    if (min > max) { int t = min; min = max; max = t; }

    unsigned long long range = (unsigned long long)max - (unsigned long long)min + 1ULL;
    if (range <= 1ULL) return min;

    unsigned int rand_bits = 0;
    unsigned int tmp = RAND_MAX;
    while (tmp) { rand_bits++; tmp >>= 1; }

    unsigned long long limit = (ULLONG_MAX / range) * range;
    unsigned long long r;
    do {
        r = 0ULL;
        unsigned int filled = 0;
        while (filled < 64) {
            r = (r << rand_bits) | (unsigned long long)rand();
            filled += rand_bits;
        }
    } while (r >= limit);

    return (int)(min + (r % range));
}

Troubleshooting tips: test with extremes (INT_MIN, INT_MAX) and with swapped inputs; add assertions to catch bad arguments. If you need high-quality or cryptographic randomness, use a proper library or OS-provided secure RNG rather than rand().

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.