【问题标题】:How can I print the volume of one polyhedron based on what users inputs?如何根据用户输入的内容打印一个多面体的体积?
【发布时间】:2018-09-29 20:46:16
【问题描述】:

编写一个程序,读取边长的多面体的第一个大写字母(“T”、“C”、“O”、“D”或“I”),并打印相应多面体的体积.如果读取的字母不是 5 个字母之一,您的程序将打印“未知多面体”。

这会将几乎每个输入值打印为“else statement”的值,但它应该根据用户输入的字母以及边的尺寸打印多面体的体积。

import math
p = str(input())
a = float(input())
T = (math.sqrt(2) / 12) * (a ** 3)
C = a ** 3
O = (math.sqrt(2) / 3) * (a ** 3)
D = (15 + 7 * math.sqrt(5)) / 4 * (a ** 3)
I = 5 * (3 + math.sqrt(5)) / 12 * (a ** 3)
if p == (math.sqrt(2) / 12) * (a ** 3) :
    print (T)
elif p == a ** 3 :
    print(C)
elif p == (math.sqrt(2) / 3) * (a ** 3) :
    print(O)
elif p == (15 + 7 * math.sqrt(5)) / 4 * (a ** 3) :
    print(D)
elif p == 5 * (3 + math.sqrt(5)) / 12 * (a ** 3) :
    print(I)
else :
    print('Polyèdre non connu')

【问题讨论】:

  • 你想要什么以及你在代码中写了什么有点混乱。试着更清楚地解释你想要什么
  • 您在这些 if 语句中究竟检查了什么?您只是从您设置到TC 等变量中重复自己。如果您想检查p 字符串值是否等于字符串"T",那么只需检查if p == "T":
  • 考虑让if 语句区分字母输入。它将清理逻辑,并将所有“数学”放在一起。
  • 好吧,程序必须计算一个多面体的面积,有 5 种多面体类型,每个多面体都有一个名称(T、C、O、D 和 I)。用户应输入其中一个字母和边的尺寸来计算多面体的体积,每个多面体都有自己的公式。如果用户输入了除上述之外的其他字母,则程序应输出消息“Unknown Polyhedrone”。
  • @Daniel:我现在明白了这个问题。在下面检查我的解决方案。它可能会帮助你

标签: python if-statement volume


【解决方案1】:

这是您想要的更正后的工作版本

import math
p = input("Enter type of polyhedral: ")
a = float(input("Enter the value of a: "))

if p == 'T':
    volume =(math.sqrt(2) / 12) * (a ** 3)
elif p == 'C':
    volume = a**3
elif p == 'O':
    volume = (math.sqrt(2) / 3) * (a ** 3)
elif p == 'D':
    volume = (15 + 7 * math.sqrt(5)) / 4 * (a ** 3) 
elif p == 'I':
    volume =  5 * (3 + math.sqrt(5)) / 12 * (a ** 3)
else:
    print('Polyèdre non connu')
    volume = "Not Yet Defined"

print ("The volume of p=%s is %s" %(p, volume))      

样本输出

Enter type of polyhedral: O
Enter the value of a: 12.45
The volume of p=O is 909.71

Enter type of polyhedral: K
Enter the value of a: 12
Polyèdre non connu
The volume of p=K is Not Yet Defined

【讨论】:

  • 知道了!这就是我一直在寻找的,但是请你解释一下最后一行代码吗?
  • 在代码的最后一行,我只是打印了多面体的体积和类型。为此,您可以使用%s 格式打印字符串。我将类型打印为p=%s,并将卷也打印为使用is %s 的字符串。定义数据类型(字符串为 %s)后,您必须将替换字符串 %s 的值放在双引号中。我使用 %s 表示体积,因为当多面体与您想要计算的不同时,我使用的是 volume = "Not Yet Defined"
  • 谢谢,它帮助了我。
  • 还有一件事,代码运行完美,但最后一行有一个错误。
  • 什么样的错误?请写出您使用的导致错误的输入
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-11-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-17
相关资源
最近更新 更多