繁体   English   中英

如何让python使用负数

[英]How to let python use negative numbers

我一直在做一个线性方程式计算器,我想知道如何让python使用负数。 像int(),float()等...

这是我的代码。

import time

print("Hello and welcome to the linear equation calculator.")

time.sleep(2)

print("Enter the first co-ordinate like this - (xx, yy): ")
coordnte1 = input()

print("Now enter the second co-ordinate like this, with the brackets, - (xx,yy): ")
coordnte2 = input()

print("Now the y-intercept: ")
yintrcpt = input()

ydif = coordnte2[1] - coordnte1[1]
xdif = coordnte2[0] - coodrnte1[0]
g = ydif / xdif

print("y = " + g + "x + " + yintrcpt)

和问题:

Traceback (most recent call last):
  File "C:/Users/Dale/Documents/GitHub/new_python_rpi_experiments/linear.py", line 17,   in <module>
    ydif = coordnte2[1] - coordnte1[1]
TypeError: unsupported operand type(s) for -: 'str' and 'str'

我是Python的新手,所以可以提供任何帮助。

您从输入中读取的是一个字符串 ,您需要提取坐标并将其转换为float ,例如:

print("Enter the first co-ordinate like this - (xx, yy): ")
s = input()

现在s = "(34, 23)"是一个字符串 ,您需要对其进行处理(消除括号,逗号等...):

coords = [float(coord) for coord in s.strip('()').split(',')]

现在,coords是一个浮点数列表(数组),您可以执行coords[0]- coords[1]等操作。

问题与负数无关。 就是input()给您一个文本字符串。 Python不知道如何对文本字符串进行减法或数学运算,即使它们恰好包含数字字符也是如此。

您将需要编写一个函数,将(10,3)形式的字符串转换为两个数字。 我将让您探索如何做,但是字符串对象的stripsplit方法可能对您有用,并且您可以在仅包含数字值的字符串上使用int()float()进行转换到整数或浮点数字变量。 例如: int('123')为您提供数字123

尝试int:

ydif = int(coordnte2[1]) - int(coordnte1[1])
xdif = int(coordnte2[0]) - int(coodrnte1[0])
ydif = float(coordnte2[1]) - float(coordnte1[1])

我认为是你的问题...

尝试使用eval将字符串转换为类型,例如

coordnte1 = eval(coordnte1)
coordnte2 = eval(coordnte2)

您可能希望将其放在try语句中,因为如果用户输入无法评估的字符串,它将失败。

暂无
暂无

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

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