类型错误:不支持 ** 或 pow() 的操作数类型:“str"和“int" [英] TypeError: unsupported operand type(s) for ** or pow(): 'str' and 'int'

查看:71
本文介绍了类型错误:不支持 ** 或 pow() 的操作数类型:“str"和“int"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是在尝试使用 Python 2.7 并从中获得乐趣,我正在尝试编写一个二次方程求解器.当 radicand 为正时,我让它工作,但是当它为负时,我会出错.即使在这个 if else 语句之后.它也不适用于大数字.感谢您的帮助.

导入数学a = raw_input("a = ")b = raw_input("b = ")c = raw_input("c = ")浮动(一)浮动(b)浮动(c)基数 = ((b**2)-4*a*c)如果基数 >= 0:打印(((0-b) + math.sqrt((b**2)-4*a*c))/(2*a))打印(((0-b) - math.sqrt((b**2)-4*a*c))/(2*a))别的:打印想象中的激进"

当我用 radicand 替换 (b**2)-4*a*c 时,我得到一个无效的语法错误,并且打印以红色突出显示.错误信息说类型错误:不支持 ** 或 pow() 的操作数类型:str"和int"
再次感谢您提供的任何见解...

解决方案

你应该替换:

float(a)

与:

a = float(a)

其他变量也类似.

语句float(a)实际上并没有将a 变成一个float,它只是简单地转换它,根据以下成绩单:

<预><代码>>>>a = raw_input("a?")一种?4.5>>>类型(一)<输入'str'>>>>浮动(一)4.5>>>类型(一)<输入'str'>>>>a = 浮点数(a)>>>类型(一)<输入'浮动'>

可以看到 a 的类型在执行 float(a) 后立即仍然 str 但是,当你执行w赋值a = float(a)时,类型变成了float.

I am just experimenting and having fun with Python 2.7 and I'm trying to write a quadratic equation solver. I had it working when the radicand is positive, but when it's negative im getting an error. even after this if else statement. it also doesnt work with big numbers. thanks for the help.

import math
a = raw_input("a = ")
b = raw_input("b = ")
c = raw_input("c = ")
float(a)
float(b)
float(c)
radicand = ((b**2)-4*a*c)
if radicand >= 0:
    print(((0-b) + math.sqrt((b**2)-4*a*c))/(2*a))
    print(((0-b) - math.sqrt((b**2)-4*a*c))/(2*a))
else:
    print "Imaginary Radical"

when i replace (b**2)-4*a*c with radicand i get an invalid syntax error and print is highlighted in red. the error message says TypeError: unsupported operand type(s) for ** or pow(): 'str' and 'int'
thanks again for any insight you can provide...

解决方案

You should replace:

float(a)

with:

a = float(a)

and similarly for the other variables.

The statement float(a) doesn't actually turn a into a float, it simply casts it, as per the following transcript:

>>> a = raw_input("a? ")
a? 4.5

>>> type(a)
<type 'str'>

>>> float(a)
4.5

>>> type(a)
<type 'str'>

>>> a = float(a)

>>> type(a)
<type 'float'>

You can see that the type of a is still str immediately after performing float(a) but, when you execute thew assignment a = float(a), the type becomes float.

这篇关于类型错误:不支持 ** 或 pow() 的操作数类型:“str"和“int"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆