如何解决python中的运行时错误-计算pyth定理
我的程序出现运行时错误,但我无法弄清楚。哪里出问题了?如果您能帮助我,将不胜感激! :) 这是代码:
P.S。我是python的新手!感谢您的帮助!
import math
n = input()
for a in range(n):
x,y = input().split()
num = math.sqrt(x**2+y**2)
print(num)
解决方法
函数input()
返回一个字符串。函数split()
返回字符串列表。您不能使用字符串进行任何数学运算。您必须先强制转换为正确的类型,然后才能执行任何操作。
尝试:
import math
n = input()
for a in range(int(n)):
x,y = input().split()
x,y = float(x),float(y) # for example,it can be int as well
num = math.sqrt(x**2+y**2)
print(num)
,
您至少有两个错误。
第一个是您的输入保留为字符串。您应该使用n = int(input())
或n = float(input())
第二个是您遇到运行时错误:
ValueError: not enough values to unpack (expected 2,got 1)
是您输入的结果。您正在尝试将该输入打包为两个单独的值。但是,同样,您只有一个。
我认为您正在寻找的更像是这样:
import math
x = float(input())
y = float(input())
num = math.sqrt(x**2+y**2)
print(num)
但是可以进一步缩短为:
x = float(input())
y = float(input())
print((x**2+y**2)**.5)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。