我正在学习Java,而我正在尝试一些小程序.我有这个问题:
/*
Compute the 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 are " + ci + " cubic inches in cubic mile.");
}
}
Run Code Online (Sandbox Code Playgroud)
输出是:
There are 1507852288 cubic inches in cubic mile.
Run Code Online (Sandbox Code Playgroud)
我知道整数的位宽是32,所以范围是:-2,147,483,648到2,147,483,647
为什么输出1507852288?它应该是2,147,483,647.
谢谢.
我正在用Herbert Schildt的书来学习Java:Java初学者指南.在那本书中出现了这段代码:
// A promotion surprise!
class PromDemo{
public static void main(String args[]){
byte b;
int i;
b = 10;
i = b * b; // OK, no cast needed
b = 10;
b = (byte) (b * b); // cast needed!!
System.out.println("i and b: " + i + " " + b);
}
}
Run Code Online (Sandbox Code Playgroud)
我不明白为什么我必须在行中使用(byte):
b = (byte) (b * b); // cast needed!!
Run Code Online (Sandbox Code Playgroud)
b被定义为一个字节,b*b的结果是100,这是一个字节的正确值(-128 ... 127).
谢谢.
我正在学习Java"Java:A Beginner's Guide"一书.这本书展示了for循环的这个例子:
// Loop until an S is typed
class ForTest {
public static void main (String args[]) throws java.io.IOException {
int i;
System.out.println ("Press S to stop.");
for (i=0; (char) System.in.read() != 'S'; i++)
System.out.println ("Pass #" + i);
}
}
Run Code Online (Sandbox Code Playgroud)
输出是:
Press S to stop.
s
Pass #0
Pass #1
Pass #2
d
Pass #3
Pass #4
Pass #5
S
Run Code Online (Sandbox Code Playgroud)
我不明白为什么每次按下不同的键盘键时,它会写三次Pass#.我认为它应该只写一次Pass#.谢谢.
我试图理解按位和移位运算符.我写了一个简单的代码来向我展示一个短类型的位.
class Shift {
public static void main (String args[]) {
short b = 16384;
for (int t = 32768; t > 0; t = t / 2) {
if ((b&t) != 0) System.out.print("1 ");
else System.out.print ("0 ");
}
System.out.println();
b = (short)(b + 2);
for (long t = 2147483648L; t > 0; t = t / 2) {
if ((b&t) != 0) System.out.print ("1 ");
else System.out.print ("0 ");
}
System.out.println();
}
}
Run Code Online (Sandbox Code Playgroud)
输出是:
C:\>java Shift
0 1 …Run Code Online (Sandbox Code Playgroud)