也许我看不到明显的东西但是:
int x1 = 2;
int y1 = 4;
int x2 = 11;
int y2 = 7;
double res = (y2-y1)/(x2-x1);
System.out.println(res);
输出:
0.0
为什么?
最佳答案
问题是你在做整数运算。您需要进行类型转换才能首先将分子或分母转换为 float (例如):
int x1 = 2;
int y1 = 4;
int x2 = 11;
int y2 = 7;
double res = (double)(y2-y1)/(x2-x1);
System.out.println(res);
如果对整数进行除法,结果将被截断为最接近的整数(产生与 floor 运算相同的结果)。例如:
0 / 2 == 0
1 / 2 == 0
2 / 2 == 1
3 / 2 == 1
等等
关于java - 除法时输出为零?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13148977/