我想制作一个简单的平方根计算器。
Class ...
'' Shared .ctor, called once the first time the class is accessed.
Shared Sub New()
dictOfAlgorithm = New Generic.Dictionary(Of String, algorithm)
End Sub
Public Shared dictOfAlgorithm As Generic.Dictionary(Of String, algorithm)
End Class
似乎我没有做错任何事情,但是,当我尝试运行程序时,在输入数字后,我遇到以下错误消息:
num = input('Enter a number and hit enter: ')
if len(num) > 0 and num.isdigit():
new = (num**0.5)
print(new)
else:
print('You did not enter a valid number.')
答案 0 :(得分:3)
您可以使用此解决方案。这里try和catch能够处理各种输入。所以你的程序永远不会失败。并且因为输入被转换为float。您不会遇到任何类型相关的错误。
try:
num = float(input('Enter a positive number and hit enter: '))
if num >= 0:
new = (num**0.5)
print(new)
except:
print('You did not enter a valid number.')
答案 1 :(得分:0)
输入函数返回字符串值。所以你需要正确地解析它
num = raw_input('Enter a number and hit enter: ')
if num.isdigit():
if int(num) > 0:
new = (int(num)**0.5)
print(new)
else:
print('You did not enter a valid number.')
答案 2 :(得分:0)
使用Math模块进行简单计算。 参考:Math module Documentation.
import math
num = raw_input('Enter a number and hit enter: ')
if num.isdigit():
num = float(num)
new = math.sqrt(num)
print(new)
else:
print('You did not enter a valid number.')