python - 不能使用特定值来计算不同的变量

标签 python python-3.x integer pythagorean

我收到一个错误,告诉我无法将两个特定值的变量相乘。

TypeError: can't multiply sequence by non-int of type 'str'

我正在尝试在 python 中为学校制定毕达哥拉斯定理。我需要将它放在 float 内才能获得十进制数。

我已经尝试过几种不同的方法,

  • 我把它放在几个值中,int、string、float 等。
  • 我刚刚尝试了很多不同的事情,这是迄今为止我得到的最好的结果。
    l_1 = float(input())
    l_1 = float(l_1)
    l_1 = str(l_1)
    print ("The long side is: " + l_1)
    l_2 = float(input())
    l_2 = float(l_2)
    l_2 = str(l_2)
    print ("The short side is: " + l_2)
    l_2 = int(l_2)
    l_1 = int(l_1)
       
    l_1 = int(l_1)
    l_2 = int(l_2)
        
    wor1 = math.sqrt(l_1 * l_1 - l_2 * l_2)
    print (wor1)

我希望输出实际是没有任何错误代码的答案,我只需要它使用给定的变量进行计算。

最佳答案

对代码进行一些更改,就可以开始了。

请注意,在计算平方根时,请注意在 sqrt 函数中传递平方的绝对差。使用这个,您可以消除小边和大边的约定。只需取两侧,代码就会为您处理这个问题。

import math

l_1 = float(input())
print ("The long side is: " + str(l_1))
l_2 = float(input())
print ("The short side is: " + str(l_2))

difference = float(l_1 * l_1 - l_2 * l_2)
# Take absolute difference since square roots of negative numbers are undefined
absolute_difference = math.fabs(difference)

# Get square root of the absolute difference 
wor1 = math.sqrt(absolute_difference)
print (wor1)

关于python - 不能使用特定值来计算不同的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58235479/

相关文章:

python - Pandas 是一段时间内的时间戳

python - 将 qcut 分配为新列

python - 当 bkgd 字符为curses.ACS_CKBOARD 时,文本显示损坏

javascript - 最小最大和 Javascript

java - 如果数组大小先验未知,如何填充数组

python - 难以理解函数的工作原理

python3.6 日志记录 - fileConfig 给出 TypeError

python - 是否有与 Laravel 4 等效的 python?

c++ - 无限大小的整数?

python - 警告用户未保存的更改将会丢失