2

我正在尝试编写一个程序来执行简单的算术运算。我希望程序提示用户输入两个数字,然后计算五个结果:

  • 总和
  • 区别
  • 产品
  • 根据两个整数的商
  • 浮点除法。

现在,我记得在Python 2中,通常有用于字符串的 raw_input 和用于数字的 input。但是,我只是在学习Python 3,默认情况下输入是一个字符串,对于数字,我必须指定我希望拥有的数字类型:即 int(input()) 或 float(input())。

因此,例如,让我们假设我想要得到这个输出(使用输入 4 和 2.5):

What is the first number? 4
What is the second number? 2.5
The sum is 6.5
The difference is 1.5
The product is 8.0
The integer quotient is 2
The floating-point quotient is 1.6

我会在Python 2中输入这段代码:

x=input ("What is the first number? ")
y=input ("What is the second number? ")

print "The sum is", x+y
print "The difference is", x-y
print "The product is", x*y
print "The integer quotient is", int(x)/int(y)
print "The floating-point quotient is", float(x)/float(y)

但是,我无法在Python 3中完成它。这是我正在使用的(错误的)代码:

x = int(input("What is the first number? "))
y = int(input("What is the second number? "))

print("The sum is: ", x+y)
print("The difference is: ", x-y)
print("The product is: ", x*y)
print("The integer quotient is: ", x/y)
print("The floating-point quotient is: ", x/y)

显然,我收到一条错误消息,因为我的第二个输入 (y) 等于 4.5,这是一个浮点数,而不是我的输入定义的整数。我没有费心将 float(x)/float(y) 作为浮点商,因为这也是矛盾的(因此是一个错误)。

我当然可以像这样放置 float 而不是 int:

x = float(input("What is the first number? "))
y = float(input("What is the second number? "))

但在这种情况下,我的产品会得到 10.0(不是 10),而且我的整数商是浮点数(1.6 而不是 2)

我发现在 Python 3 中我不能要求输入的通用类型号(无需指定它是 float 还是 int)真的很令人沮丧。因此,我坚持使用这样简单的程序,并且非常感谢任何解决方案/解释。

4

1 回答 1

3

您可以尝试将输入解析为 a int,如果这不起作用,请将其视为 a float

def float_or_int(x):
    try:
        return int(x)
    except ValueError:
        return float(x)

x = float_or_int(input("What's x?"))
y = float_or_int(input("What's y?"))

要在 Python 3 中获得地板除法,您必须向//操作员明确要求它:

print("The integer quotient is:", x//y)

请注意,这种“整数商”运算对于浮点输入实际上没有意义。

于 2013-09-21T20:15:20.373 回答