c - 为什么 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...
我在大学作业时注意到了这一点...
解决方案
rand() % 1112
可能变为 0 到 1111 范围内的值。
您应该这样做rand() % (1112 - 1000 + 1) + 1000
,因为 1000 的偏移量应该在 0 到1112 - 1000
.
推荐阅读
- php - 使用重力形式的 WordPress 婚礼 RSVP
- angular - 有没有办法以声明方式翻译模板中的插值?
- c++ - 使用 glDrawPixels() 在 OpenGL 上绘制一个像素
- python - 使用 setup.py 进行跨平台部署
- mysql - SQL query to find users with apps with no releases
- reactjs - how to delete a single item using axios in react
- java - 在android项目中集成Liblinphone 4
- android - 这是活动内存泄漏吗?
- javascript - How can i get this timer to start on click instead of on page load?
- javascript - 使用 Ajax.BeginForm 发送邮件在服务器上不起作用