0

円柱の体積と表面積を計算するこのプログラムを作成しようとしています。私は現在、そのボリューム部分をコーディングしています。ただし、出力画面では、小数点以下が 2 桁あります。それが示している:

シリンダーの容積は193019.2896193019.2896cm³

なぜ2つあるのですか?

その後、ユーザーが希望する小数点以下の桁数 (dp) をプログラムに尋ねさせようとしています。これどうやってするの?

現在のコードは次のとおりです。

print("Welcome to the volume and surface area cylinder calculator powered by Python!")
response = input("To calculate the volume type in 'vol', to calculate the surface area, type in 'SA': ")
if response=="vol" or response =="SA":
    pass
else:
    print("Please enter a correct statement.")
    response = input("To calculate the volume type in 'vol', to calculate the surface area, type in 'SA': ")

if response=="vol":
    #Below splits 
    radius, height = [float(part) for part in input("What is the radius and height of the cylinder? (e.g. 32, 15): ").split(',')] 
    PI = 3.14159 #Making the constant PI
    volume = PI*radius*radius*height
    print("The volume of the cylinder is" + str(volume) + "{}cm\u00b3".format(volume))
4

2 に答える 2

9

を2回補間しています:

print("The volume of the cylinder is" + str(volume) + "{}cm\u00b3".format(volume))

一度だけで済みます:

print("The volume of the cylinder is {}cm\u00b3".format(volume))

この関数の良い点.format()は、数値を特定の小数点以下の桁数にフォーマットするように指示できることです。

print("The volume of the cylinder is {:.5f}cm\u00b3".format(volume))

ここでは、小数点以下 5 桁を使用します。その数もパラメータ化できます。

decimals = 5
print("The volume of the cylinder is {0:.{1}f}cm\u00b3".format(volume, decimals))

デモ:

>>> volume = 193019.2896
>>> decimals = 2
>>> print("The volume of the cylinder is {0:.{1}f}cm\u00b3".format(volume, decimals))
The volume of the cylinder is 193019.29cm³
>>> decimals = 3
>>> print("The volume of the cylinder is {0:.{1}f}cm\u00b3".format(volume, decimals))
The volume of the cylinder is 193019.290cm³

input()andを使用int()して、ユーザーから小数の整数を求めることにします。

于 2013-10-03T20:56:11.427 に答える
0

ユーザーに必要な小数点以下の桁数を尋ねることについての質問に答えるには、次のようにします。

#! /usr/bin/python3

decimals = int (input ('How many decimals? ') )
print ('{{:.{}f}}'.format (decimals).format (1 / 7) )
于 2013-10-03T21:01:08.710 に答える