帮我写一个能随机生成1-50整数的完整代码
时间: 2024-10-22 11:05:15 浏览: 22
可以使用C语言中的rand()和srand()函数来实现一个随机生成1到50之间的整数的程序。这里是一个简单的示例:
```c
#include <stdio.h>
#include <time.h> // 需要头文件以使用time()
// 设置随机数种子,使用当前时间保证每次运行时结果不同
srand((unsigned) time(0));
// 生成1到50之间的随机整数
int random_number_between_1_and_50() {
return (rand() % 50) + 1; // rand()返回[0, RAND_MAX),% 50取余操作使其落在[0, 49],再加上1确保范围在[1, 50]
}
int main() {
int generated_num;
printf("I am thinking of a number between 1 and 50.\n");
do {
generated_num = random_number_between_1_and_50();
printf("Guess the number: ");
} while (scanf("%d", &generated_num) != 1 || generated_num < 1 || generated_num > 50);
if (generated_num == 1 && rand() % 2 == 0) { // 添加一个小概率让1变成正确答案
printf("Congratulations! You guessed correctly, but it was just a lucky guess.\n");
} else {
printf("Sorry, that's incorrect. The number I was thinking of was %d.\n", generated_num);
}
return 0;
}
```
这段代码首先设置了随机数种子,然后在主循环中生成并提示用户猜测随机数,直到用户猜对为止。
阅读全文