给出的示例中还是出现了结果为负数,超出了0到100的范围,请加以修改程序,使程序符合要求
时间: 2024-03-24 13:38:51 浏览: 10
非常抱歉,我在前面的回答中没有考虑到这种情况。以下是修改后的程序,可以确保生成的加减法题目的结果在0到100以内:
```python
import random
import datetime
def generate_test_paper(n):
"""
生成n道加减法,结果在0到100以内的测试卷
"""
test_paper = []
for i in range(n):
x = random.randint(0, 100)
y = random.randint(0, 100)
op = random.choice(['+', '-'])
if op == '+':
result = x + y
if result > 100:
y = 100 - x
result = 100
else:
result = x - y
if result < 0:
y = x
x = random.randint(y, 100)
result = x - y
test_paper.append((x, op, y, result))
return test_paper
def save_test_result(test_result):
"""
记录测试结果,包括测试日期和每道题是否正确
"""
date = datetime.date.today()
with open('test_result.txt', 'a') as f:
f.write(str(date) + '\n')
for result in test_result:
if result:
f.write('正确\n')
else:
f.write('错误\n')
f.write('\n')
def take_test():
"""
进行测试
"""
n = 50
test_paper = generate_test_paper(n)
test_result = []
for x, op, y, result in test_paper:
print('{} {} {} = '.format(x, op, y), end='')
answer = int(input())
if answer == result:
print('回答正确')
test_result.append(True)
else:
print('回答错误')
test_result.append(False)
save_test_result(test_result)
if __name__ == '__main__':
take_test()
```
在生成测试卷时,如果加法的结果超出了100,则将y的值设为100-x,这样可以保证结果为100;如果减法的结果小于0,则将x的值设为一个在y到100之间的随机数,这样可以保证结果不小于0。这样修改后,生成的加减法题目的结果就一定在0到100以内了。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)