让计算机来想一个数,然后让用户来猜用户每输入一个数,就告诉它是大了还是小了,直到用户猜中为止,最后还要告诉用户它猜了多少次。
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
int main() {
srand(time(0)); //生成随机数
int n = rand() % 100 + 1; //随机数取余,始终为两位数
int a;
int times = 0;
printf("Please enter the number you guessed\n");
do
{
scanf("%d", &a);
times ++;
if (a>n)
{
printf("The number you entered is too large. Please enter again\n");
}
else if(a<n)
{
printf("The number you entered is too small. Please enter again\n");
}
} while (a!=n);
printf("Congratulations, you guessed right. You guessed %d times", times);
}