简体   繁体   English

使用不同的变量类型进行计算

[英]Compute using different variable types

I'm reading Java: The Complete Reference by Herbert Schildt right now and here is one thing that is not really clear for me. 我现在正在阅读Herbert Schildt撰写的《 Java:完全参考》,这对我来说还不是很清楚。 In the chapter about Integers it says that the long type should be used when big, whole numbers are needed. 在有关整数的章节中,它说当需要大的整数时,应使用型。 The code example from the book: 书中的代码示例:

// Compute distance light travels using long variables

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

        int lightspeed;
        long days;
        long seconds;
        long distance;

        // approximate speed of light in miles per second

        lightspeed = 18600;

        days = 1000; // specify number of days here

        seconds = days * 24 * 60 * 60; // convert to seconds

        distance = lightspeed * seconds; // compute distance

        System.out.print("In " + days + " days light will travel about " + distance + " miles.");

    }
}

Upon execution console provides me with such the result: 执行后,控制台会为我提供以下结果:

"In 1000 days light will travel about 16070400000000 miles."

According by my logic, days and seconds vars should be int too, while their values are less than 2 147 483 647. 根据我的逻辑,天和秒var也应为int ,而其值应小于2147483647。

At this example days = 1000 and seconds = 86 400 000, so the values aren't that big. 在此示例中,day = 1000,seconds = 86400 000,因此值并不大。

But when I declare variables like this: 但是当我这样声明变量时:

int lightspeed, days, seconds;
long distance;

I've strange result and for now I can accept it at no way. 我得到的结果很奇怪,现在我无法接受。

"In 1000 days light will travel about -1367621632 miles."

Help me please. 请帮帮我。

When both seconds and lightspeed are declared as int , lightspeed * seconds is computed as the multiplication of int s, which causes an overflow (since 16070400000000 > 2147483647). 如果将secondslightspeed都声明为intlightspeed * seconds计算为int s的乘积,这将导致溢出(因为16070400000000> 2147483647)。

You can still leave them as int if you cast lightspeed or seconds to long , which will force the multiplication to be performed on long s : 如果将lightspeedsecondslong ,仍然可以将它们保留为int ,这将强制对long s进行乘法:

distance = (long)lightspeed * seconds; 

or 要么

distance = lightspeed * (long)seconds; 

Yes, only the distance is relevant, as Eran pointed out. 是的,正如伊兰指出的那样,只有距离才是重要的。

This behaviour is quite easy to remember if you just think of divison. 如果您只是想到分手,这种行为就很容易记住。

as above a / b performs integer division (truncation) given that a and b are integers whereas 假设a和b是整数,则上述a / b执行整数除法(截断)

(double) a / b

would return a double. 会返回双倍。

Note that the cast always refers to what follows after it. 请注意,类型转换始终是指其后的内容。 so in the case of an expression comprising of two integers only the first integer is casted to double. 因此,在包含两个整数的表达式中, 只有第一个整数会强制转换为双精度。

` `

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

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