简体   繁体   中英

private static final double is 0

我试图使用以下行来指定一个双常量,任何人都可以帮我解释为什么在运行时这个常量的值为0.0

private static final double CONSTANT = 1/2;

1 and 2 are interpreted as integers and produce integer result of division. Add D at the end to make them interpreted as doubles.

private static final double CONSTANT = 1D/2D;

The constant ends up with a value of 0.0 because the result of integer division is an integer, truncated. So your the value of your initialization is 0 , not 0.5 . To force a double result, make one or both of the operands a double :

private static final double CONSTANT = 1/2.0;  // or 1/2D, or even 1D/2D 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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