I write in Windows on DevC ++. Generation of random numbers, everything works correctly except for the range 1000 - 1112, I can not understand the reason. gives values ​​ranging from a thousand to 2200. What is the problem tell me?

#include <stdio.h> #include <stdlib.h> #include <time.h> main() { srand(time(NULL)); for (int i = 1; i <= 5; i++) //1 to 2 { printf("%d\n", 1 + rand() % 2); } for (int i = 1; i <= 5; i++) //1 to 100 { printf("%d\n", 1 + rand() % 100); } for (int i = 1; i <= 5; i++) //0 to 9 { printf("%d\n", 0 + rand() % 9); } for (int i = 1; i <= 5; i++) //1000 to 1112 { printf("%d\n", 1000 + rand() % 1112); } for (int i = 1; i <= 5; i++) //-1 to 1 { printf("%d\n", -1 + rand() % 1); } for (int i = 1; i <= 5; i++) //-3 to 11 { printf("%d\n", -3 + rand() % 11); } system("PAUSE"); } 

    1 answer 1

    If I understand everything correctly, in your opinion, the error is here:

     printf("%d\n", 1000 + rand() % 1112); 

    This line will display a random number from 1000 to 2111 (1000 + 1112-1). Perhaps this is a typo if you wanted to get a range of 1000-1112. Can be replaced by printf("%d\n", 1000 + rand() % 112); and it works.

    • Thanks, it works, but I cannot understand why it initially does not work because I indicate the beginning and end of the range, namely, from 1000 to 1112? After all, according to the logic of 1000 to 112 in general should give an error? Can you explain or write where I can find information on this issue? - Stee1House
    • one
      @steelhouse, 1000 + rand ()% 1112 - here * the sum * (and not the beginning and end of the range!) of two numbers 1000 and some random from 0 to 1111 (because rand ()% 1112 is random by module 1112). Therefore, their sum lies in the range from 1000 to 2111. - Alexey Lobanov
    • one
      I just misunderstood, on the Internet, there were examples of the "initial value + rand ()% final value" and I took an example from this. Now I will understand a little better. - Stee1House
    • @steelhouse, you better understand what the% operation does and what rand returns. - dzhioev