Pythonを使用して円の面積と周囲長を計算するアプリケーションを作成します

Document 对象参考手册Python3 例

Pythonを使用して、円の面積と周囲長を計算する簡単なアプリケーションを作成します。ユーザーが円の半径を入力すると、プログラムは円の面積と周囲長を出力します。

例

import math

def calculate_area(radius):
    return math.pi * radius ** 2

def calculate_circumference(radius):
    return 2 * math.pi * radius

def main():
    radius = float(input("円の半径を入力してください: "))
    area = calculate_area(radius)
    circumference = calculate_circumference(radius)
    print(f"円の面積: {area:.2f}")
    print(f"円の周囲長: {circumference:.2f}")

if __name__ == "__main__":
    main()

コードの説明:

  1. import math:Pythonのmathモジュールをインポートして、math.pi円周率の値を取得します。
  2. calculate_area(radius):円の面積を計算する関数を定義します。公式はπ * r^2。
  3. calculate_circumference(radius):円の周囲長を計算する関数を定義します。公式は2 * π * r。
  4. main():メイン関数です。ユーザーが入力した半径を取得し、上記の2つの関数を呼び出して面積と周囲長を計算し、結果を出力します。
  5. if __name__ == "__main__"::スクリプトが直接実行された場合にのみ実行されるようにしますmain()関数。

出力結果: ユーザーが入力した半径が5の場合、プログラムは次のように出力します:

请输入圆的半径: 5
圆的面积为: 78.54
圆的周长为: 31.42

Document 对象参考手册Python3 例

その他の拡張