自动铸造 [英] Automatic casting
问题描述
我必须编写从用户获取一个数字 n
的程序,然后计算和:s = 1/1 + 1/2 + ... + 1 / n。
I have to write program that gets a number n
from the user, and then calculates the sum: s = 1/1 + 1/2 + ... + 1/n.
我写了以下代码:
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner unos = new Scanner(System.in);
System.out.println("n=?");
int n = unos.nextInt();
double s = 0.0;
for (int i = 1; i <= n; i++) {
s = s + (1.0 / i);
}
System.out.println("s=" + s);
}
}
Java如何决定转换int值 i into double in this statement:
How does Java decide to convert the int value i
into double in this statement:
s = s + (1.0 / i);
推荐答案
Java语言规范中定义的其他类型第5章 - 转化和宣传 a>。
The rules that govern what type gets converted/promoted to what other type are defined in the Java Language Spec Chapter 5 - Conversions and Promotions.
对于大多数算术运算,请查看二进制数值推广部分。
Specifically for most arithmetic operations, look at the Binary Numeric Promotion section.
一对操作数,每一个都必须表示数值类型的值,以下规则按顺序使用加宽转换(§5.1.2),以便根据需要转换操作数:
When an operator applies binary numeric promotion to a pair of operands, each of which must denote a value of a numeric type, the following rules apply, in order, using widening conversion (§5.1.2) to convert operands as necessary:
- 如果任一操作数的类型为double,则另一个转换为double。
- 否则,如果任一操作数的类型为float,
在您的情况下,1.0是双精度型,因此 i
被转换为double(加宽转换)。由于 s
已经是双精度,因此不需要进一步的转换。
In your case, 1.0 is a double, so i
is converted to a double (widening conversion). Since s
already is a double, no further conversion is necessary.
这篇关于自动铸造的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!