Pythonで円錐の体積と表面積を計算する

私のPythonの復習とトレーニングがてら取り組んでおります。今回はPythonで円錐の体積と表面積を計算する方法です。

体積と表面積の求め方は(自分の記憶との答え合わせのため)Googleで調べているので、おそらく間違ってないと思いますが、万が一間違っていても、今回はあくまでPythonの練習が焦点ですのでお許しください。

Pythonコード

コードはこんな感じになりました。

円周率πを使うためにmathをインポートしてます。これ前に良く使った気がするなぁ…。

import math

radius = int(input("> What is length of radius or the cone?"))
height = int(input("> What is height of the cone?"))
side_cone_length = int(input("> What is length of the side of the cone?"))
pi = math.pi

print("> Let me calculate...")
print("> Volume 1")
volume1 = pi * radius**2 * height / 3
print(f"{volume1}")

print("> Let me calculate the volume in a different way to make sure the calculation is correct.")
radius_square = radius**2
volume2_temp = pi * radius_square * height
volume2 = volume2_temp / 3
print(f"{volume2}")

if volume1 == volume2:
  print("> Both results are the same, so calculations are good!!")
else:
  print("> Results are different, something is wrong in the calculations...OTL")

print("> OK!! Let's move on to surface area")
surface_area1 = (radius + side_cone_length) * radius * pi
print("> Surface Area 1")
print(surface_area1)

print("> Let me calculate the surface area in a different way to make sure the calculation is correct.")
surface_area_temp = radius + side_cone_length
surface_area2 = surface_area_temp * radius * pi
print(f"{surface_area2}")

if surface_area1 == surface_area2:
  print("> Both results are the same, so calculations are good!!")
else:
  print("> Results are different, something is wrong in the calculations...OTL")

今回はinput()を整数化してますが、小数点を扱えるようにしたり、計算結果も小数点以下の数字が多いので四捨五入したりしたいですね。将来的には。

実行結果

こちらがGoogle Colabで実行した結果です。

振り返り

今回は複数の加減乗除をするので計算結果が合っているのか気になりました。例えば「A + B = C」等と言う計算は間違えようがありませんが、「A + B/3 * C = D」のような、計算の順番で答えが変わりそうな気がしたので、2種類ずつ計算方法を変えてみました。

ほら、あの、乗除が先とか括弧内が先に計算とか言うあれです。どんなものだったかうろ覚えです…苦笑

めっさん
  • めっさん
  • 当サイトの管理人。ニューヨークの大学を飛び級で卒業。その後日系企業でグローバル案件に携わる。大小様々な企業を転々としながら、マレーシアやアメリカへの赴任経験を持つ。バイリンガルITエンジニアとしていかに楽に稼ぐか日々考えている。年齢は秘密だけど定年も間近かな。

コメントする

メールアドレスが公開されることはありません。 が付いている欄は必須項目です