【发布时间】:2015-02-08 23:19:25
【问题描述】:
我正在 Udacity 学习 Python 课程,我正在尝试自己解决这个问题,而不看答案。或许你可以给我一个逻辑提示?
以下是说明以及我目前掌握的内容。我们还没有学习条件语句,所以我不能使用它们。我们只学习了如何分配/打印变量、字符串、索引字符串、子序列和 .find。他们刚刚在最后一个练习中介绍了 str 命令。
# Given a variable, x, that stores the
# value of any decimal number, write Python
# code that prints out the nearest whole
# number to x.
# If x is exactly half way between two
# whole numbers, round up, so
# 3.5 rounds to 4 and 2.5 rounds to 3.
# You may assume x is not negative.
# Hint: The str function can convert any number into a string.
# eg str(89) converts the number 89 to the string '89'
# Along with the str function, this problem can be solved
# using just the information introduced in unit 1.
# x = 3.14159
# >>> 3 (not 3.0)
# x = 27.63
# >>> 28 (not 28.0)
# x = 3.5
# >>> 4 (not 4.0)
x = 3.54159
#ENTER CODE BELOW HERE
x = str(x)
dec = x.find('.')
tenth = dec + 1
print x[0:dec]
////
所以这让我将字符打印到小数点,但我不知道如何让计算机检查“第十”是 > 4 还是 并且打印出来根据答案的东西。
我想如果“第十个”不是 > 4,我可能会走得足够远让它返回 -1,但我不知道如何让它打印 x[0:dec] 如果 它是 4。
:/
有人可以在正确的方向上轻推我吗?
【问题讨论】: