【发布时间】:2023-03-28 12:00:01
【问题描述】:
计划 1
int sum = 30;
double avg = sum / 4; // result is 7.0, not 7.5 !!!
VS.
方案 2
int sum= 30
double avg =sum/4.0 // Prints lns 7.5
这是因为程序 1 中的 '4' 是一个字面整数吗?所以 30/4 会给我 7。但是,由于这种数据类型是双精度的,所以我们需要添加一个 .0 来结束。所以'7.0'
程序 2 有 4.0,它充当文字双精度。 int/double 总是会给出 double ,因为它更精确。所以我们得到'7.5'。我不明白 double 数据类型对结果做了什么......它真的不需要做任何事情,因为 double 数据类型的条件已经满足。(从计算中得到最精确的结果)。
我错了吗?我鼓励你纠正我!这就是我学习的方式.. :)
【问题讨论】:
-
您的标题表明混淆是围绕
println的行为,而在我看来问题实际上与除法运算符有关。 -
it really doesn't need to do anything since the conditions of the double data type are already satisfied.??这是什么意思? -
@JonSkeet 看来,他的问题是
why the result is getting printed like that:)
标签: java