当前位置:首页 > 编程技术 > 正文

rand()如何产生负数

rand()如何产生负数

1. 乘以负数: 你可以将 `rand( ` 的返回值乘以一个负数,例如 -1,来得到一个负随机数。 ```c int n = -1 rand( ; ```2. 使用范...

1. 乘以负数:

你可以将 `rand()` 的返回值乘以一个负数,例如 -1,来得到一个负随机数。

```c

int n = -1 rand();

```

2. 使用范围限制:

```c

int n = -10 (rand() % 11);

```

3. 使用 `rand()` 的返回值范围:

```c

int n = -50 (rand() % (100 50 + 1));

```

4. 使用 `rand()` 和 `srand()`:

```c

include

int main() {

srand((unsigned int)time(NULL));

int n = -1 rand();

return 0;

最新文章