写一段计算一百以内加减法的程序
时间: 2023-05-19 21:01:27 浏览: 59
好的,以下是一段计算一百以内加减法的程序:
```python
import random
def generate_question():
"""生成一个加减法问题"""
a = random.randint(1, 100)
b = random.randint(1, 100)
operator = random.choice(['+', '-'])
if operator == '+':
answer = a + b
else:
answer = a - b
question = f"{a} {operator} {b} = ?"
return question, answer
def main():
"""主函数,循环生成问题并接受用户输入答案"""
correct_count = 0
total_count = 0
while True:
question, answer = generate_question()
print(question)
user_answer = input("请输入答案:")
try:
user_answer = int(user_answer)
except ValueError:
print("请输入一个整数!")
continue
if user_answer == answer:
print("回答正确!")
correct_count += 1
else:
print(f"回答错误,正确答案是 {answer}")
total_count += 1
print(f"你已经回答了 {total_count} 道题,其中 {correct_count} 道题回答正确。")
if __name__ == '__main__':
main()
```
这个程序会随机生成一百以内的加减法问题,并等待用户输入答案。如果用户输入的答案与正确答案相同,则会输出“回答正确!”;否则会输出“回答错误,正确答案是 xxx”,其中 xxx 是正确答案。程序会一直循环生成问题,直到用户主动退出。
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)