Reputation: 45
I'm doing rounded-integer batch conversion of Fahrenheit to Celsius (yes, for codeabbey.com), and I've spent hours on this to get stuck in something that looks like it should run smoothly. Specifically, my results are all zero. So somewhere in the for
loop, probably in the assignment of j
and k
, the math is breaking down. I've looked at it again and again. Why am I getting zeroes in my results?
fahrenheit = raw_input().split() # Dump copy-and-pasted values into a list.
iter = int(fahrenheit.pop(0)) # Remove the first value and use it as a counter.
celsius = [] # Make an empty list for results.
x = 0 # Index counter
for i in fahrenheit:
j = (int(i)-32) * (5.0/9)
k = (int(i)-32) * (5/9)
if float(j) == k:
celsius.append(j)
elif j > 0: # For positive results
if (j - k) >= 0.5: # If integer value needs +1 to round up.
celsius.append(k+1)
else:
celsius.append(k)
elif j < 0: # For negative results
if (k - j) >= 0.5:
celsius.append(k+1) # If integer values needs +1 to bring it closer to 0.
else:
celsius.append(k)
else:
celsius.append(k) # If the result is 0.
print ' '.join(celsius)
The formatting of the data calls for this strange setup. The first number in the data is not a temperature to test. All others are. So 5 80 -3 32 212 71
calls for five calculations: 80, -3, 32, 212, and 71 converted to Celsius.
Upvotes: 0
Views: 93
Reputation: 35088
As noted by Peter Wood in his comment, 5/9
evaluates as 0 due to integer division. However, the rest of your program could be simplified by using Python's built in round function.
>>> [round(x) for x in [26.0, 26.4, 26.5, 26.9]]
[26.0, 26.0, 27.0, 27.0]
You can then rewrite like:
celsius = [int(round((f-32)*5.0/9.0)) for f in fahrenheit[1:]]
Upvotes: 2