简体   繁体   English

如何解决浮点计算问题?

[英]How do I fix a Floating Point Calculation issue?

So, last week, I got some work sent to me for Python 3, and one of the questions goes as follows: "Write (a) program which inputs the year. Your program should output whether it is a leap year or not. To work out if it is a leap year, test whether it is exactly divisible by 4."所以,上周,我收到了一些关于 Python 3 的工作,其中一个问题如下:“编写 (a) 输入年份的程序。你的程序应该输出它是否是闰年。到计算它是否是闰年,测试它是否能被 4 整除。”

This is what I've got so far:这是我到目前为止所得到的:

yearStr = input("Please input a year: ")
year = float(yearStr)

calculation = year / 4

print(calculation)

if calculation == .0:
    print("This is a leap year.")
else:
    print("This is not a leap year.")

When I run the program, the IF statement doesn't work as intended.当我运行程序时,IF 语句不能按预期工作。 Could you help me, please?请问你能帮帮我吗?

Division does not yield zero if the number is evenly divisible, so this method cannot work.如果数字是可整除的,除法不会产生零,因此这种方法不起作用。

Rather, use the modulo ( % ) operator to get the remainder of the division:相反,使用模 ( % ) 运算符来获取除法的余数:

year = int(yearStr)
calculation = year % 4
if calculation == 0: # leap year
    ...

And note that strictly speaking, leap year determination is a bit more complex than just being divisible by four.请注意,严格来说,确定闰年比被 4 整除要复杂一些。 But it'll do for the next 79 years.但它会在接下来的 79 年里发挥作用。

Your problem is the performance of the code.您的问题是代码的性能。 To check if the year is leap, you have to put different conditions.要检查年份是否为闰年,您必须设置不同的条件。 You can now use this code:您现在可以使用此代码:

year = int(input("Please input a year: "))

if ((year%400 == 0) or ((year%4 == 0) and (year%100 != 0))):
    print("This is a leap year.")
else:
    print("This is not a leap year.")

You are comparing calculation with 0, which is true only if the year was 0. You can check if integer value is equal to number itself.您正在将计算与 0 进行比较,这仅在年份为 0 时才成立。您可以检查整数值是否等于数字本身。

calculation = year / 4

print(calculation)

if int(calculation) == calculation:
    print("This is a leap year.")
else:
    print("This is not a leap year.")

Still, this is not a good way to solve this problem, there is a remainder operation - %.尽管如此,这并不是解决这个问题的好方法,还有一个余数运算 - %. For example 5 % 2 = 1 .例如5 % 2 = 1 You can use it this way:你可以这样使用它:

yearStr = input("Please input a year: ")
year = float(yearStr)

print(calculation)

if calculation % 4 == 0:
    print("This is a leap year.")
else:
    print("This is not a leap year.")

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

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