python - 如何解决 TypeError:'float' 对象在 python 中不可迭代
问题描述
我正在尝试创建一个使用二次公式求解 x 的代码。对于输出,我不希望它显示虚数……只有实数。我将平方根内的值设置为等于名为“root”的变量,以确定该值是否为 pos/neg(如果为 neg,则解决方案将是虚构的)。
这是代码。
import math
print("Solve for x when ax^2 + bx + c = 0")
a = float(input("Enter a numerical value for a: "))
b = float(input("Enter a numerical value for b: "))
c = float(input("Enter a numerical value for c: "))
root = math.pow(b,2) - 4*a*c
root2 = ((-1*b) - math.sqrt(root)) / (2*a)
root1 = ((-1*b) + math.sqrt(root)) / (2*a)
for y in root1:
if root>=0:
print("x =", y)
elif root<0:
print('x is an imaginary number')
for z in root2:
if root>=0:
print("or x =", z)
elif root<0:
print('x is an imaginary number')
这是错误代码:
File "/Users/e/Documents/Intro Python 2020/Project 1/Project 1 - P2.py", line 25, in <module>
for y in root1:
TypeError: 'float' object is not iterable
错误发生在以下行:
for y in root1:
如何修复此错误?
解决方案
我知道你在这里使用二次方程。可迭代对象类似于列表。具有超过 1 个元素的变量。在你的例子中
root1 是单个浮点值。root2 也是一个浮点值。出于您的目的,您不需要任何带有“for”的行。尝试删除 for y 和 for z 行并运行您的代码。
为了帮助您理解,浮点值只是一个带有小数的数字。
推荐阅读
- scala - Spark Streaming Kafka:使用 spark-submit 运行时 ByteArrayDeserializer 的 ClassNotFoundException
- amazon-web-services - AWS 配置运行状况检查 EC2
- pandas - Pandas groupby,求和并填充原始数据框
- ios - Xcode 在丢弃所有更改后删除 pod 文件文件夹和架构
- pandas - 如何有条件地重置熊猫数据框中的滚动最大初始值/行?
- c# - 使用 linq 在相关表中选择实体属性
- rust - 为什么调用消耗后调用 BufReader::fill_buf 返回的字节数比我预期的少?
- html - 带有`position:sticky;`的粘性页脚
- vue.js - VueJS - 未知的本地操作类型:addProductToCart,全局类型:cart/addProductToCart
- visual-studio - TFS 2010 Team Foundation 服务不可从服务器获得
. 无法连接到远程服务器