c语言随机数字猜答案
以下是一个简单的C语言随机数字猜答案的程序:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
int answer, guess;
srand(time(NULL)); // 设置随机数种子
answer = rand() % 100 + 1; // 生成1~100之间的随机数
printf("猜一个1~100之间的数字:\n");
do {
scanf("%d", &guess);
if (guess > answer) {
printf("太大了,再猜一次:\n");
} else if (guess < answer) {
printf("太小了,再猜一次:\n");
}
} while (guess != answer);
printf("恭喜你,猜对了!答案是%d。\n", answer);
return 0;
}
程序先生成一个1~100之间的随机数作为答案,然后让用户输入猜测的数字,根据猜测的数字与答案的大小关系给出提示,直到猜对为止。程序使用了time库和srand函数来设置随机数种子,以保证每次运行程序时生成的随机数不同
原文地址: https://www.cveoy.top/t/topic/em6e 著作权归作者所有。请勿转载和采集!