简体   繁体   English

为什么我打印的时候f的值总是0?

[英]Why is the value of f when I print it always 0?

I wrote this little program in java, and the value of f is always 0. I dont see the logical error.I did this exact same thing in python and it works flawlessly.我在 java 中编写了这个小程序,f 的值始终为 0。我没有看到逻辑错误。我在 python 中做了完全相同的事情并且它完美地工作。 I dont get what im missing.我不明白我缺少什么。

public class factorial{
    public static void main(String[] args){

        int n = 1;
        int f = 1;
        while (true){
            n++;
            f = f * n;
            System.out.println(f);

        }
    }
}

In fact, you do not always get 0. Your output looks like this:事实上,你并不总是得到 0。你的 output 看起来像这样:

2
6
24
120
720
5040
40320
362880
3628800
39916800
479001600
1932053504
1278945280
2004310016
2004189184
-288522240
-898433024
109641728
-2102132736
-1195114496
-522715136
862453760
-775946240
2076180480
-1853882368
1484783616
-1375731712
-1241513984
1409286144
738197504
-2147483648
-2147483648
0
0
0
0
...

This is problem with int overflow in infinite loop.这是无限循环中 int 溢出的问题。

I don't familiar with Python, but if you want something int without overflow, you can look at BigInteger class in Java. Python我不熟悉,但是如果你想要int而不溢出,你可以看看Java中的BigInteger class。

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

相关问题 当我打印地图数据时,为什么总是按顺序排列? - When I print map data I always get in sorted order why? Java线程:解释为什么不总是打印变量的最新值 - Java Thread: explain why not always print the newest value of variable 为什么在从 android 本机模块调用方法时总是得到 null 值而不是字符串值 - Why I got null Value instead of the string value always when calling a method from android native modules 为什么当我打印 ArrayList 时得到列表值而不是参考值 - why am I getting List values instead of reference value, when i print ArrayList 为什么我尝试登录时代码中的身份验证始终返回False值? - Why Authentication in my Code always return False value when i try to login? 为什么该程序总是打印1 - Why does this program always print 1 为什么 SongName[i]!= null 在它应该是 F 时评估为 T - Why does songName[i]!= null evaluates to T when it should be F 当我调用方法 f() 时,控制台中什么也没有出现。 为什么? - When i call the method f() nothing appears in the console. Why? 为什么在使用 Java DSL 时,我必须在入站 webflux 网关上使用.fluxTransform(f -> f)? - Why do I have to use .fluxTransform(f -> f) on an inbound webflux gateways when using Java DSL? 为什么在运行单元测试时@Value 总是 null? - Why @Value are always null when run unit-test?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM