i'm learning java , i'm trying little programs. have problem one:
/* compute number of cubic inches in 1 cubic mile. */ class inches { public static void main(string args[]) { int ci; int im; im = 5280 * 12; ci = im * im * im; system.out.println("there " + ci + " cubic inches in cubic mile."); } }
the output is:
there 1507852288 cubic inches in cubic mile.
i known width in bits integer 32, range is: -2,147,483,648 2,147,483,647
why output 1507852288? should 2,147,483,647.
thank you.
when result crosses maximum values of int overflowed ie, integer overflow. may better want use long
instead of int
.
you may interested read: integer overflow , underflow in java.
arithmetic integer operations performed in 32-bit precision. when resultant value of operation larger 32 bits (the maximum size int variable can hold) low 32 bits taken consideration , high order bits discarded. when msb (most significant bit) 1 value treated negative.
Comments
Post a Comment