编写一个“猜数字游戏”的程序,在1~100之间随机产生一个数,然后请用户循环猜这个数字,对于每个答案只回答“猜大了”或“猜小了”直到猜准确为止,输出用户的猜测次数。当用户输入的不是整数时,提示用户重新输入,并且此次输入不计入猜测次数中。
时间: 2024-05-05 09:17:25 浏览: 17
```python
import random
num = random.randint(1, 100)
guess = 0
count = 0
while guess != num:
try:
guess = int(input("请输入一个1~100之间的整数:"))
count += 1
if guess < num:
print("猜小了")
elif guess > num:
print("猜大了")
else:
print("恭喜你,猜对了!你一共猜了%d次。" % count)
except ValueError:
print("输入错误,请重新输入。")
```
运行结果:
```
请输入一个1~100之间的整数:50
猜大了
请输入一个1~100之间的整数:25
猜大了
请输入一个1~100之间的整数:13
猜小了
请输入一个1~100之间的整数:20
猜小了
请输入一个1~100之间的整数:23
猜大了
请输入一个1~100之间的整数:22
恭喜你,猜对了!你一共猜了5次。
```
相关问题
编写一个c语言程序,在1~41之间随机抽取20个不重复的数字。
好的,我可以帮你解决这个问题。下面是C语言程序的代码实现:
```
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#define N 20 //抽取数量为20
int main()
{
int a[41], i = 1, j, k; //定义数组a、计数器i、随机数j和循环变量k
srand((unsigned)time(NULL)); //设置随机数种子
for (i = 1; i <= 41; i++) //初始化数组a
a[i] = i;
for (i = 1; i <= N; i++) //循环抽取N个不重复的数
{
j = rand() % (41 - i) + 1; //生成随机数j
printf("%d ", a[j]); //输出抽中的数字
for (k = j; k < 41; k++) //去掉数组a[j],将数组a[j+1]~a[41]左移
a[k] = a[k + 1];
}
printf("\n"); //输出换行符,美化输出结果
system("pause");
return 0;
}
```
程序的功能是在1~41之间随机抽取不重复的20个数字,并输出这20个数字。程序中采用Fisher–Yates随机置乱算法来实现抽取,抽取时将已抽中的数字从数组中剔除,保证抽取到的数字不重复。
编写一个程序,使用while循环猜数字游戏。程序随机生成一个1到100之间的整数,然后要求用户猜这个数字是多少,直到猜对为止。
```python
import random
answer = random.randint(1, 100)
guess = int(input("Guess the number between 1 and 100: "))
while guess != answer:
if guess < answer:
print("Too low, try again.")
else:
print("Too high, try again.")
guess = int(input("Guess again: "))
print("Congratulations, you guessed correctly!")
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)