【问题标题】:Entry level python code passing str to int error [closed]入门级python代码将字符串传递给int错误[关闭]
【发布时间】:2021-12-17 06:07:55
【问题描述】:

我在尝试根据用户输入计算数字时遇到了一些问题。

高度的输入是第一个问题。用户放入 5.9 英尺,当然是作为字符串输入的。

尝试转换为 INT,我假设它会四舍五入到 6,然后它的高度乘以自身除以重量。

但是,我如何知道如何将字符串转换为 INT 似乎并不适用于此

``` 
print("Today we are going to calculate your BMI")
weight = input("What is your weight? ")
height = input("What is your height? ")
    
#weight = 175
#height = 5.9  
    
weight_int = int(weight)
height_int = int(height*height)
    
print("Congratulations your BMI is " + weight_int / height_int)
```
When I run this, I get the following error:
```

回溯(最近一次通话最后一次): 文件“”,第 1 行,在 TypeError:不能将序列乘以“str”类型的非整数



【问题讨论】:

  • 在将高度变量转换为 int 之前,您将其自身相乘,这可能是您的问题。您还应该在问题中包含您的错误,以帮助其他人帮助您!
  • 将height 转换为int 与您为weight 所做的相同 --> height = int(height); height_int = int(height*height)
  • As @PirateNinjas + 当看起来(来自您的 cmets)您会接受 float 时,为什么要将输入转换为 int?
  • 问题需要整数作为输出

标签: python string integer


【解决方案1】:

在转换为 int 之前,您看起来要乘以自己的身高。而是稍后再做,例如:

print("Today we are going to calculate your BMI")
weight = input("What is your weight? ")
height = input("What is your height? ")

weight_float = float(weight)
height_float = float(height)

print("Congratulations your BMI is " + str(weight_float / (height_float * height_float)))

注意关键变化:

  1. 高度在尝试相乘之前从字符串转换为浮点数。对于您的用例,浮点数可能比 int 更好。
  2. 我们在 print 语句中计算完整的 bmi
  3. 我们需要将 bmi 转换回字符串以与字符串连接

您也可以在最后一部分使用 f 字符串:

print(f"Congratulations your BMI is {weight_float / (height_float * height_float)}")

【讨论】:

    猜你喜欢
    • 2021-12-05
    • 1970-01-01
    • 2021-04-13
    • 2013-08-26
    • 2018-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-18
    相关资源
    最近更新 更多