为什么代码会产生这个答案?[Python]

2024-04-19 09:12:34 发布

您现在位置:Python中文网/ 问答频道 /正文

基本上我是在设置一个代码,但由于一些随机的原因,它总是说答案是错误的。你知道吗

所以,假设它是“10 x 10”&我会说它是“100”

但是代码对我说,“I'm sorry the answer is 100

为什么代码会产生这个答案?

代码如下:

附言:我知道我不必为所有的事都做Num_(NUMBER)!你知道吗

from random 
import randint 
import random

correct = 0

for i in range (3):
  num_1 = randint (1, 10)
  num_2 = randint (1, 10)
  prob1 = num_1*num_2

print (“What’s %d x %d? “ (num_1, num_2))
ans1 = input ()

If ans1 == prob1:
  print (“That’s the correct answer!  /n”)
  correct = correct +1                                                             
else:
  print (“No I’m afraid the answer is %d. /n” & (prob1))

for n in range (3):
  num_3 = randint (1, 10)
  num_4 = randint (1, 10)
  prob2 = num_3+num_4

print (“What’s %d + %d? “ (num_3, num_4))
ans2 = input ()

If ans2 == prob2:
  print (“That’s the correct answer!  /n”)
  correct = correct +1
else:
  print (“No I’m afraid the answer is %d. /n” & (prob2))

for m in range (4):
  num_5 = randint (1, 10)
  num_6 = randint (1, 10)
  prob3 = num_5 - num_6

print (“What’s %d - %d? “ (num_5, num_6))
ans3 = input ()

If ans3 == prob3:
  print (“That’s the correct answer!  /n”)
  correct = correct +1
else:                                                                                                                              
  print (“No I’m afraid the answer is %d. /n” & (prob3))

print (“I asked you 10 questions, you got %d of them right. “ %(correct))
exit()

Tags: the代码answerinforinputifis
1条回答
网友
1楼 · 发布于 2024-04-19 09:12:34

探测变量是整数类型。用户给出的答案是一个字符串。用以下方法进行测试:

print type(ans1)

print type(prob1)

因此,您需要将用户的输入转换为整数:

if int(ans1) == prob1

相关问题 更多 >