简体   繁体   English

我的电话号码加不上我的算法,我也不知道为什么

[英]My number won't add up for my algorithm and I don't know why

print ("Perimeter for Total House Floor Remodeling Calculator")   
print(" ")   
width1 = input ("Please enter the width of the floor: ")   
length1 = input ("Please enter the length of the floor: ")   
print (" ")   
length = length1 * 2   
width = width1 * 2   
perimeter = (length + width)   
print ("The perimeter of the floor is: ",perimeter)    

Once I input my number and lets say I put in 5 for the width and 5 for the length, my perimeter would come out as 5555 instead of 20. I'm new to coding so any help is greatly appreciated. 输入数字并说出5的宽度和5的长度后,我的周长将显示为5555而不是20。我是编码的新手,所以对您的帮助非常感谢。

input() function gives you strings, you need to convert them to integer before doing any calculation. input()函数为您提供字符串,您需要在进行任何计算之前将它们转换为整数。 Try: 尝试:

width1 = int(input("Please enter the width of the floor: "))   
length1 = int(input("Please enter the length of the floor: ")) 

Python can do multiplication operation between strings, which repeats them. Python可以在字符串之间进行乘法运算,从而重复它们。 IE: '5'*3 gives you '555' because it is a string. IE: '5'*3为您提供'555'因为它是一个字符串。 While 5*3 gives 15 because it is an integer. 5*3给出15因为它是整数。

You are capturing the data from input() which is a string. 您正在从input()捕获数据,它是一个字符串。 You need to cast it to a number. 您需要将其强制转换为数字。 When you have a string aka "12" and you run "12"*2 it will output "1212". 当您有一个字符串,又名“ 12”并且运行“ 12” * 2时,它将输出“ 1212”。

raw_output = input("Enter a number: ")
print("Type of raw_output: {0}".format(type(raw_output))
actual_integer = int(raw_output)
print("Type of actual_integer: {0}".format(type(actual_integer))

From the help function 从帮助功能

Help on built-in function input in module builtins:

input(...)
    input([prompt]) -> string

Read a string from standard input.  The trailing newline is stripped.
If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError.
On Unix, GNU readline is used if enabled.  The prompt string, if given,
is printed without a trailing newline before reading.

Since data types don't need to be explicitly mentioned in Python, you'll have to type cast (forcibly convert to some other data type) your inputs for them to be considered as integers. 由于不需要在Python中明确提及数据类型,因此您必须对您的输入进行类型转换(强制转换为其他数据类型),才能将它们视为整数。

width1 = int(input("Please enter the width of the floor: "))
length1 = int(input("Please enter the length of the floor: ")) 

This should work! 这应该工作!

I'm not sure which version of python you're using, but on 2.7.13 that I have on my computer, your code works just fine. 我不确定您使用的是哪个版本的python,但是在计算机上的2.7.13上,您的代码可以正常工作。 Check which version you're got, and let us know. 检查您获得的版本,并告诉我们。

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

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