繁体   English   中英

作业帮助:TypeError:不支持的操作数类型-:'str'和'str'

[英]Homework Help: TypeError: unsupported operand type(s) for -: 'str' and 'str'

很难弄清楚我做错了什么。 我是 Python 入门课程的学生。 教授没有很好地解释事情。

我们正在尝试计算三角形的角度。 他希望我们使用 .split 以便我们可以一次性输入所有值。 从那里去。 我想这就是我的问题所在。 这是我的代码。

import math
user_input = (input('Enter three points: '))

numbers = user_input.split(',')

x1,y1,x2,y2,x3,y3 = numbers[0], numbers[1], numbers[2], numbers[3], 
numbers[4], numbers[5]

a = math.sqrt((x2 - x3) * (x2 - x3) + (y2 - y3) * (y2 - y3))
b = math.sqrt((x1 - x3) * (x1 - x3) + (y1 - y3) * (y2 - y3))
c = math.sqrt((x1 - x2) * (x1 + x2) + (y1 - y2) * (y1 - y2))

A = math.degrees(math.acos((a * a - b * b - c * c) / (-2 * b * c)))
B = math.degrees(math.acos((b * b - a * a - c * c) / (-2 * a * c)))
C = math.degrees(math.acos((c * c - b * b - a * a) / (-2 * a * b)))

print("The three angles are ", round(A * 100) / 100.0,
  round(B * 100) / 100.0, round(C * 100) / 100.0)

当我尝试为三角形输入值时,出现此错误。 我很新,所以我不确定如何解决这个问题。

Enter three points: 1, 1, 6.5, 1, 6.5, 2.5

回溯(最近一次调用最后一次):
<module> 中的文件“C:\\Users\\smwht\\Desktop\\Python Stuff\\ComputeAngles.py”,第 12 行
a = math.sqrt((x2 - x3) * (x2 - x3) + (y2 - y3) * (y2 - y3))
类型错误:不支持 - 的操作数类型:“str”和“str”

因为您尝试将字符串用于算术运算符。 这将有助于

numbers = [float(i) for i in user_input.split(',')]

错误的代码可能

当您使用input().split()您会得到一个字符串列表,因此您应该将其转换为浮点数,这是使用列表理解的示例:

numbers = [float(x) for x in user_input.split(',')]

input()返回一个字符串, split()返回一个字符串数组,您可以使用float()将它们转换为数字:

x1,y1,x2,y2,x3,y3 = float(numbers[0]), float(numbers[1]), float(numbers[2]), float(numbers[3]), float(numbers[4]), float(numbers[5])

或者更少的代码:

x1,y1,x2,y2,x3,y3 = map(float, numbers)

甚至更少:

x1,y1,x2,y2,x3,y3 = map(float, input('Enter three points: ').split(','))

一个有很多评论的升级版:

# you can import just the functions you want, and
#   call them directly like sqrt() instead of math.sqrt()
from math import acos, degrees, sqrt

# functions make it easy to reuse, document and test bits of code

def get_floats(prompt, sep=None):
    # A docstring - if you type "help(get_floats)" it will display this.
    """
    Prompt until one or more numbers are entered
    """
    nums = []
    while not nums:  # repeat until nums is not empty
        string = input(prompt)
        try:
            # a list comprehension - do something to each item in a list,
            #   and return the results as another list.
            # In this case, each piece of the split string gets converted to float()
            nums = [float(s) for s in string.split(sep)]
        except ValueError:
            # exceptions help you to handle unexpected problems,
            #   like if someone tries to enter 'banana' when asked for a number
            pass
    return nums

def dist(p1, p2):
    """
    Return Cartesian distance between two points
    """
    # zip() is a very useful function for combining several lists in parallel -
    #   if you call zip(list1, list2, list3) it will give you the first
    #   item from each list, then the second item from each, etc.
    # In this case, we treat each point as a list of coordinates - [x1, y1, z1]
    #   and when we zip two points we get the coordinates in each dimension:
    #   zip([x1, y1, z1], [x2, y2, z2])  ->  [[x1, x2], [y1, y2], [z1, z2]]
    #
    # The loop,  (b - a) ** 2 for a, b in zip(p1, p2)
    #   is a generator expression - it's like a list comprehension,
    #   but it yields a value at a time instead of a whole list at once.
    #   It is sometimes a little bit slower, but takes less memory.
    # 
    # For each pair of coordinates we square the difference -
    #   then we sum all of the squares and take the root,
    #   which gives us Cartesian distance.
    #
    # The neat thing is, this loop doesn't care how many dimensions you give it -
    #   it will work on 2d points, or 3d, or 5d. If you give it a pair
    #   of 27-dimensional points, it will happily return the distance
    #   in 27-dimensional space.
    return sqrt(sum((b - a) ** 2 for a, b in zip(p1, p2)))

def get_angle(a, b, c, use_degrees=True):
    """
    Given the lengths of three sides of a triangle,
      return the angle opposite side c
    """
    # using cosine law
    angle = acos((a * a + b * b - c * c) / (2 * a * b))
    if use_degrees:
        angle = degrees(angle)
    return angle

def main():
    # get points of a triangle
    p1 = get_floats("Enter point 1: ", ",")
    p2 = get_floats("Enter point 2: ", ",")
    p3 = get_floats("Enter point 3: ", ",")

    # get side lengths
    a = dist(p2, p3)
    b = dist(p1, p3)
    c = dist(p1, p2)

    # get angles
    A = get_angle(b, c, a)
    B = get_angle(a, c, b)
    C = get_angle(a, b, c)

    # show results using string formatting (automatically rounds the result)
    print(
        "The three angles are {:0.2f}, {:0.2f} and {:0.2f}"
        .format(A, B, C)
    )

main()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM