Java 中的整数除法
原文:https://www.studytonight.com/java-examples/integer-division-in-java
在本教程中,我们将学习 Java 中的整数除法。假设我们有两个Integer
类型的变量a=25
和b=5
,我们想要执行除法。
当涉及到保持精度或避免精度的决定时,主要是在除法运算时,因为在进行除法运算时,很有可能会失去精度。
简单除法的例子
在给定的示例中,我们有三个 int 类型的变量a
、b
、c
,我们将a
、&、b
的除法存储到c
中。我们建议您运行这个示例,观察输出,并将您的观察结果与我们下面讨论的内容进行匹配。
public class StudyTonight
{
public static void main(String[] args)
{
int a = 25;
int b = 5;
int c = a / b;
System.out.println(a+"/"+b+"="+c);
}
}
25/5=5
在上面的情况下,除法会很精细,因为所有变量都是整数形式的,5
将25
完全除。想想10/3
肯定c
不能存储3.3333...
,因为它是一个整型变量,只能存储整数数据,只能保存 3
。在以下情况下,它不考虑提醒。
示例:丢失数据
这里,我们将两个整数相除,并将结果存储到 int 中,这将导致数据丢失,因为整数不包含小数位值。
public class StudyTonight
{
public static void main(String[] args)
{
int a = 10;
int b = 3;
int c = a / b;
System.out.println(a+"/"+b+"="+c);
}
}
10/3=3
现在让我们提出进行实数除法的想法,我们将在double.
中存储值
例子
在下面给出的代码中,为了观察当我们将变量的数据类型从 float 更改为 int 时会发生什么的输出,反之亦然。你会得到整数或实数。
public class StudyTonight
{
public static void main(String[] args)
{
int ans1 = 10 / 3;
double ans2 = 10.0 / 3;
double ans3 = 10 / 3.0;
double ans4 = 10.0 / 3.0;
double ans5 = 10 / 3;
System.out.println("10 / 3 = "+ans1);
System.out.println("10.0 / 3 = "+ans2);
System.out.println("10 / 3.0 = "+ans3);
System.out.println("10.0 / 3.0 = "+ans4);
System.out.println("10 / 3 = "+ans5);
}
}
10/3 = 3 10.0/3 = 3.3333333333335 10/3.0 = 3.33333333335 10.0/3.0 = 3.3333333333335 10/3 = 3.0
结论:
在实现了所有上述代码之后,我们可以根据除数和被除数的数据类型得出一些重要的结论
int / int = int
double / int = double
int / double = double
双倍/双倍=双倍