2016-11-16 11 views
1

3つの温度の平均を計算するPython関数を作成しようとしています。私はPythonの初心者ですので、正しい軌道に乗っていることを確認したかったのです。 3つの数値の平均を計算するPython関数を作成する

def average(temp_one, temp_two, temp_three): 
    avg = (int(temp_one) + int(temp_two) + int(temp_three))/3 
    return avg 

は、その後、私は3つの温度を要求し、平均値を算出し、作成した関数を使用する必要があります。
これは私がこれまで持っているものです。平均出力には小数点以下1桁が含まれていなければなりません。

この部分については、わかりません。何か助けていただきありがとうございます!

答えて

2

1.も参照小数第1位とfloatを出力しますあなたの計算では、いくつかの精度を失うintに不要なキャストを行っています。実際には、小数点以下を切り捨てるため、人為的に平均値を下げます。

2.あなたが書いた機能を使用していません。代わりに、整数除算//で計算コードを繰り返します。注:

5/2 == 2.5 # floating point division 
5 // 2 == 2 # integer division 

ここでは、情報も失われています。

3.出力を小数点以下1桁にフォーマットする必要があります。これは最高のstring formatting

このように使用して行われます:

def average(temp_one, temp_two, temp_three): 
    return (temp_one + temp_two + temp_three)/3 
    # why cast to int and lose precision 

# read your 3 float inputs ... 

avg = average(temp_one, temp_two, temp_three) # actually use your function 
print('{:.1f}'.format(avg)) # format output 
+0

良い固体の答え...悪いにあなたは文句を言わないテスト中に利用可能である:P +1 –

+0

ませんか?私たちはオープンインターネット試験をしていましたが、DはおそらくSD1にはありませんでしたが – schwobaseggl

+0

私の新しいコードは... > def average(temp_one、temp_two、temp_three): >> return(temp_one、temp_two、temp_three)/ 3 >>>平均=平均(temp_one、temp_two、temp_three) しかし、上記の「平均」を強調表示する構文エラーが無効です。 – Victoria

0
"%0.1f"%my_float 
#or 
"{0:0.1f}".format(my_float) 
#or 
"{my_float:0.1f}".format(my_float=my_float) 

python format strings

関連する問題