c语言随机数生成1到100
时间: 2023-10-16 13:20:27 浏览: 58
你可以使用stdlib.h头文件中的rand()函数来生成随机数,再通过取余运算限定在1到100之间。以下是一个简单的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
int random_num;
// 使用当前时间作为随机数种子
srand(time(NULL));
// 生成1到100之间的随机数
random_num = rand() % 100 + 1;
printf("随机数为:%d\n", random_num);
return 0;
}
```
请注意,为了使每次生成的随机数不相同,需要使用srand()函数设置随机数种子。上述代码中使用当前时间作为随机数种子,因为时间会不断变化,所以生成的随机数也会不同。
相关问题
c语言随机数生成1到100猜数
以下是使用C语言生成1到100的随机数进行猜数的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
int target, guess, attempts = 0;
// 设置随机数种子
srand(time(0));
// 生成1到100之间的随机数
target = rand() % 100 + 1;
printf("猜数游戏开始!\n");
do {
printf("请输入你猜测的数字(1-100):");
scanf("%d", &guess);
attempts++;
if (guess > target) {
printf("猜大了!\n");
} else if (guess < target) {
printf("猜小了!\n");
} else {
printf("恭喜你猜对了!答案是%d\n", target);
break;
}
} while (1);
printf("你猜了%d次\n", attempts);
return 0;
}
```
c语言随机数生成1到100的两个数
代码如下:
```c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
int num1, num2;
srand((unsigned int)time(NULL)); // 设置随机种子为当前时间
num1 = rand() % 100 + 1; // 生成1到100之间的随机数
num2 = rand() % 100 + 1;
printf("随机数1: %d\n", num1);
printf("随机数2: %d\n", num2);
return 0;
}
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)