【问题标题】:Homework Help: TypeError: unsupported operand type(s) for -: 'str' and 'str'作业帮助:TypeError:不支持的操作数类型 -: 'str' 和 'str'
【发布时间】:2017-09-06 20:09:04
【问题描述】:

很难弄清楚我做错了什么。我是 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

回溯(最近一次通话最后一次):

中的文件“C:\Users\smwht\Desktop\Python Stuff\ComputeAngles.py”,第 12 行 a = math.sqrt((x2 - x3) * (x2 - x3) + (y2 - y3) * (y2 - y3))
TypeError: 不支持的操作数类型 -: 'str' 和 'str'

【问题讨论】:

标签: python


【解决方案1】:

因为您尝试使用字符串作为算术运算符。这会有所帮助

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

可能是代码错误

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      【解决方案3】:

      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(','))
      

      【讨论】:

      • 这是我使用您的修复程序时得到的。现在有什么交易?回溯(最后一次调用):文件“C:\Users\smwht\Desktop\Python Stuff\ComputeAngles.py”,第 14 行,在 中 c = math.sqrt((x1 - x2) * (x1 + x2 ) + (y1 - y2) * (y1 - y2)) ValueError: 数学域错误
      • 因为math.sqrt(...) 内部的评估数字是负数。你想计算什么?
      • 没关系!这是因为在我的一个 () 里面我有一个 +,而在另一个里面我有一个 -。我的错。我的程序现在可以工作了!感谢您的帮助!
      【解决方案4】:

      包含大量 cmets 的扩展版本:

      # 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()
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-02-20
        • 2018-12-06
        • 1970-01-01
        • 2021-01-03
        • 2018-04-22
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多