需要使用python代码进行小修复

时间:2017-03-12 11:36:33

标签: python python-3.x

我是初学者并且已经开始学习python。我应该制作一个程序,其中用户必须猜测1到100之间的随机数。如果猜测不正确那么它也没关系我应该显示消息,例如:“你猜的是远离数字”或者如果猜测在数字范围的10个单位内,我应该显示消息,例如你在数字范围内的10个单位。

现在我在这里处理一种逻辑错误。解释一下,如果随机数为42且用户输入32,则显示消息:“你在数字范围内有10个单位。”这很好,但是当我输入32时......它再次显示:“你的数字范围是10个单位。”

我应该在if-else中做什么来修复代码。我需要显示用户是否在10个单位的范围内,以便猜测其他我必须打印你远离猜测。

from random import *
from time import *

number= randint(1,100)
print(number)
start=time()

guess=0
while guess!=number:
    guess=int(input())
    if number-guess <=10 :
        print("you are in range of 10 units to the number to be guessed.")
    else:
        print("You are very far in guess from that number.")


elapsed=time()-start
print("Time taken to guess the number correctly is ",elapsed)

2 个答案:

答案 0 :(得分:2)

我检查了你的代码,没有任何错误,它非常好但导致错误的唯一原因是你必须在导入数学&#34;之前写下&#34; time-start& #34; 你的代码应该是:

     std::array<int, 15> remainder= {{0}};
     remainder_count = 15;
     //...     
     if (num > 0 && num <= 65535)
     {
         while (num > 0)
         {
             remainder.at(remainder_count) = num % 2; //... exception thrown

from random import * from time import * import math number= randint(1,100) print(number) start=time() guess=0 while guess!=number: guess=int(input()) if abs(number-guess) <=10 : print("you are in range of 10 units to the number to be guessed.") else: print("You are very far in guess from that number.") elapsed=time()-start print("Time taken to guess the number correctly is ",elapsed)

答案 1 :(得分:1)

正如Elmex80s写的那样,你必须将number-guess <=10更改为abs(number - guess) <=10,因为:生成的数字是20,你现在输入120,你有-100,这是&lt; 10.所以最终的代码使这个正常工作:

from random import *
from time import *

number= randint(1,100)
print(number)
start=time()

guess=0
while guess!=number:
    guess=int(input())
    if abs(number - guess) <=10 :
        print("you are in range of 10 units to the number to be guessed.")
    else:
        print("You are very far in guess from that number.")


elapsed=time()-start
print("Time taken to guess the number correctly is ",elapsed)

enter image description here