-4

// This is the code its part of my college assignment

    #include <stdio.h>
    #include <stdlib.h>// header file for rand and srand function
    #include <time.h>
    int main()
    {
        srand(time(0)); //  time is used for different values
        int result = rand() % 1112 + 1000; // 1112 is max value & 1000 is min value. Also This formula worked in range between (-999 to 999)
        printf("%d", result);
        return 0;
    }
Output:
1702
1810 and so on...

I noticed this during my college assignment...

3 Answers3

2

rand() % 1112 may become values in the range 0 to 1111.

You should do rand() % (1112 - 1000 + 1) + 1000 because the offset from 1000 should be in the range 0 to 1112 - 1000.

MikeCAT
  • 73,922
  • 11
  • 45
  • 70
  • ...because the offset from 1000 should be in the range 0 to 1112 - 1000. I am not getting this?? please explain. I will be thankful to you – captain anas Apr 21 '21 at 11:42
  • @captainanas "the offset from 1000 should be in the range 0 to 1112 - 1000" means the offset from 1000 should be in the range 0 to 112. So adding the offset to 1000 produces a number in the range 1000 to 1112 as required. – Ian Abbott Apr 21 '21 at 11:48
  • @IanAbbott Got it. – captain anas Apr 21 '21 at 11:51
1

Your formula is wrong. you need to follow this

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

in your case

result = rand() % (1112 + 1 - 1000 ) + 1000;

what you have wrote will generate numbers from 0 to 1111 then it will add another 1000 to the generated number ..

1

We have 2021 so use C++11 solution: std::uniform_int_distribution.

    std::random_device rd;
    std::mt19937 gen(rd());

    std::uniform_int_distribution<int> distrib(1000, 1112);
    for (int n=0; n<10; ++n)
        std::cout << distrib(gen) << '\n';

Here is nice explanation why and how to use it

Marek R
  • 32,568
  • 6
  • 55
  • 140