我必须编写猜数字游戏的代码,但我不知道如何生成随机数。 random 函数只生成负数。
我目前的代码:
#include <iostream>
#include <stdlib.h>
#include <time.h>
using namespace std;
int main(){
srand(time(NULL));
int N=rand()%1000+-1000;
return 0;
}
最佳答案
The code that I have so far only generates negative numbers.
rand()%1000
的最大值是999
。如果向其中添加 -1000
,它将始终为负数。试试 rand() % 2001 - 1000
。
关于c++ - 如何生成一个介于 1000 和 -1000 C++ 之间的随机数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42461041/