首页 > 解决方案 > 为什么 rand() %max+min 公式在(1000 到 1112)之间没有给出所需的输出?

问题描述

// 这是我大学作业的代码

    #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...

我在大学作业时注意到了这一点...

标签: c

解决方案


rand() % 1112可能变为 0 到 1111 范围内的值。

您应该这样做rand() % (1112 - 1000 + 1) + 1000,因为 1000 的偏移量应该在 0 到1112 - 1000.


推荐阅读