Java整数-双除法混淆 [英] Java integer-double division confusion

查看:195
本文介绍了Java整数-双除法混淆的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

程序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"

Is this because the '4' in program 1 is acting as a literal integer? so 30/4 would give me 7. However since this data type is a double, we need to add a .0 to end. so '7.0'

程序2具有4.0,它充当字面量的double. int/double总是会给出double值,因为它更精确.所以我们得到"7.5".我不明白是什么双重数据类型对结果做..它真的不需要做任何事情,因为已经满足了双重数据类型的条件.(计算出最精确的结果).

Program 2 has 4.0 which is acting as a literal double. an int/double would always give double because it more precise. so we get '7.5'. I don't understand what double data type is doing to the result though.. it really doesn't need to do anything since the conditions of the double data type are already satisfied.(have the most precise result out of the computation).

我错了吗?我鼓励你纠正我!这就是我的学习方式.. :)

Am I wrong? I encourage you to correct me! This is how I learn.. :)

推荐答案

这是一个整数除法(因为它涉及两个整数)

This is an integer division (because it involves two integers)

int sum = 30;  
double avg = (sum / 4); // result is 7

整数除法,将四舍五入到最接近的整数.

Integer division, will round down to the nearest integer.

但是,这是两次除法(因为4.0是两次)

However, this is a double division (because 4.0 is a double)

int sum= 30   
double avg = (sum/4.0) //  result is 7.5

这是预期的行为,并且对转换的定义都很明确.不用猜测.看看有关转换的 java文档

This is the expected behaviour, and the conversion are all well defined. No need to guess. Take a look at the java docs about conversion.

int或long值到float或long的扩展转换 值翻倍,可能会导致精度损失-也就是说,结果 可能会丢失该值的某些最低有效位.在这个 情况下,生成的浮点值将正确舍入 整数值的版本,使用IEEE 754舍入到最接近模式

A widening conversion of an int or a long value to float, or of a long value to double, may result in loss of precision - that is, the result may lose some of the least significant bits of the value. In this case, the resulting floating-point value will be a correctly rounded version of the integer value, using IEEE 754 round-to-nearest mode

这篇关于Java整数-双除法混淆的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆