注册 登录
编程论坛 Python论坛

猜数程序,提交时提示错误,但是自测时时对的

莫珞lili 发布于 2016-09-09 11:48, 2491 次点击
在自学6.00.1x 计算机科学和Python编程导论的时候,有一个练习题是猜数程序。然后我的代码是这样的
程序代码:
low = 0
high = 100
ans = (low + high)/2
print 'Please thinkof a number between 0 and 100!'
print 'Is your secret number ' + str(ans) + '?'
check = raw_input("Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly.")

while check != 'c':
    if check =='h':
        high =ans
    elif check == 'l':
        low = ans
    else:
        print('Sorry, I did not understand your input.')
        print 'Is your secret number ' + str(ans) + '?'
        check = raw_input("Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly.")

    ans = (low + high)/2
    print 'Is your secret number ' + str(ans) + '?'
    check = raw_input("Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly.")

if check == 'c':
    print 'Game over. Your segggcret number was: '+str(ans)
但是在提交的时候,测试出了这么个问题。
只有本站会员才能查看附件,请 登录

但是我自己拿91作为猜测数,运行了程序又是对的。求大神指教

9 回复
#2
莫珞lili2016-09-09 11:49
对了,用的时python2.x的
#3
Valenciax2016-09-09 21:05
试试这个

程序代码:

low = 0
high = 100
mid = (high + low)/2

num = raw_input("Please think of a number between 0 and 100!")

while mid != num:
    print ( "Is your secret number " + str(mid) + "?")
    herp = raw_input("Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly. ")

    if herp == 'c':
        break
    elif herp == 'l':
        low = mid
        #mid = int(mid + high)/2
    elif herp == 'h':
        high = mid
        #mid = int(mid + low)/2
    else:
        print"Sorry, I did not understand your input."
    mid = int(low + high)/2
print "Game over. Your secret number was: " + str(mid)


[此贴子已经被作者于2016-9-9 21:08编辑过]

#4
莫珞lili2016-09-10 09:24
首先,终于有人回答了,感觉python论坛好像和别的比起来有点。然后感谢大神。但是我主要是想知道为什么会出现我这种情况。实现的方法和程序应该是有很多种,毕竟大家思考方式不一样
#5
书生牛犊2016-09-10 10:11
回复 4楼 莫珞lili
简单来说就是你的逻辑是错误的,不信你可以对比一下楼主的输出和你的输出。

你们两的输出必然是不一样的!!!


#6
莫珞lili2016-09-10 14:35
我觉得2楼的代码和我的代码逻辑是有一点不同。但是不是我出现问题的原因。
我上面图上面的错误,是说在程序预期中,我应该输出“Please think of a number between 0 and 100!”的地方,输出功能已经结束了
我自己测试过。我的判断功能并没有错。而且和正确的预期输出的内容是一样的

#7
莫珞lili2016-09-10 14:36
回复 5楼 书生牛犊
我觉得2楼的代码和我的代码逻辑是有一点不同。但是不是我出现问题的原因。
我上面图上面的错误,是说在程序预期中,我应该输出“Please think of a number between 0 and 100!”的地方,输出功能已经结束了
我自己测试过。我的判断功能并没有错。而且和正确的预期输出的内容是一样的
#8
莫珞lili2016-09-10 17:03
明白了。谢谢两位。分数就给2楼,怪我没有自己看你的程序
#9
书生牛犊2016-09-10 17:45
跟你讲一件事。平台上评判程序对错是逐行做字符串比较

比如说一个程序让你从1 print到100.如果你写的程序从0 print 到100,那么平台在接收到第一个0的时候就已经结束了程序,后面的不会继续运行。

这就是为什么我明明都没看到你的完整代码运行起来是什么效果,仅凭“ERROR:Falling on first line”就断定你的逻辑出错了。这句话的意思应该是你的输出第一行就已经和平台希望看到的正确答案不一样了


[此贴子已经被作者于2016-9-10 17:46编辑过]

#10
莫珞lili2016-09-12 17:22
回复 9楼 书生牛犊
谢谢~会继续努力
1