Udacity CS101 HW01-Q-9
Given a variable x, that stores the value of any decimal number.
Write Python code to print out the nearest whole number x.
You can assume x is not negative.
x = 3.14150 –> 3 (not 3.0)
x = 27.63 –> 28
Observe that when rounding a number you always look at the very first number after the decimal point.
If that number >= 5 (5,6,7,8,9) you round up, meaning add 1 to the number before the decimal point.
If that number is < 5(0,1,2,3,4) you round down – adding nothing to the number before the decimal point.
Some more example :
5.67 –> 6.
5.25 –> 5.
blah blah blah
This is my attempt:
1. Create a string mapping : ‘0123456789’
2. Convert x to string and store in a variable.
3. Find the first number after the decimal point position in the string.
4. Dvide the number(position) by 5 to find whether to add 1 or not to x. (x is the original number).
Fact: If you integer divide a number within the range: 0-9 by 5, you will know exactly what number to add to the whole part.
For example :
5 / 5 = 1 remain 0
6 / 5 = 1 remain 1
7 / 5 = 1 remain 2
8 / 5 = 1 remain 3
9 / 5 = 1 remain 4
The quotient is all 1, that is what we concern about.
FOr number < 5, dividing it by 5 always get 0.
Then add to x the quotient.
5. Convert x to string
6. Print out x only take the integer part.
#put whatever value of x you want here pos = "0123456789" #the position to map the number to plus x_string = str(x) #convert x to str to find in pos #find in pos the first character temp = pos.find(x_string[x_string.find('.')+1:x_string.find('.')+2]) x = x + temp/5 # > 5 --> + 1; else + 0 x = str(x) #convert to str x = x[:x.find('.')] #take only the whole number print x
NOTE: In practice, you can easily round number with the function round in python.