cs101 ยป

Unit -1 Challenge Questions

'Challenge questions' are labeled with Gold Stars and are intentionally more difficult than the normal homework questions.

Not every student is expected to correctly solve every problem. Challenge questions are intended to take more time, and provoke more thought than the normal questions. The more difficult the question is, the more Gold Stars it will be labeled with. You shouldn't be discouraged if you don't solve them.

Question 9 - Rounding numbers (2 Gold Stars)

In this question, we encourage you to try to solve the problem using only concepts that have been taught in unit one. This problem can be solved without using any other functions, or control statements, so try to solve it using only what has been covered in class so far.

Converting a Number to a String

The str function can convert any number into a string.

>> str(89)

Techniques Required

It is possible to solve this problem using only materials presented in the problem description and in lecture.

Rounding Rule

Round 3.5 up to 4.

Large Numbers

Your submission does not need to work with numbers above 100,000.

# 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.14159


num = x+0.5
s = str(num)
decimal = s.find('.')
print s[:decimal]xx