简体   繁体   中英

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. 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.

At this example days = 1000 and seconds = 86 400 000, so the values aren't that big.

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).

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 :

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

(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.

`

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