public class Main {
public static void main(String[] args) {
long product = 1L;
product = (9 * 9 * 9 * 9 * 9 * 9 * 9 * 9 * 9 * 9 * 9 * 9 * 9);
System.out.println(product);
product = 9L;
for (int i = 0; i != 12; i++) {
product *= 9;
}
System.out.println(product);
}
}
Run Code Online (Sandbox Code Playgroud)
输出:-754810903
2541865828329 //这个是正确的
在您的第一次尝试中,您无法确定结果long.因此 - 它溢出为int.
product = (9L * 9 * 9 * 9 * 9 * 9 * 9 * 9 * 9 * 9 * 9 * 9 * 9);
Run Code Online (Sandbox Code Playgroud)
那是因为int数据类型不足以占用那么多的价值.
将其转换为long.
product = (9L * 9 * 9 * 9 * 9 * 9 * 9 * 9 * 9 * 9 * 9 * 9 * 9);
Run Code Online (Sandbox Code Playgroud)
或至少先抛出它.但请确保获得long数据类型值.否则它将无法工作,你永远不会得到那个结果.你想要的:)