问题
Maybe I can't see obvious thing but:
int x1 = 2;
int y1 = 4;
int x2 = 11;
int y2 = 7;
double res = (y2-y1)/(x2-x1);
System.out.println(res);
Output:
0.0
Why?
回答1:
you need to initially define those variables as doubles and it should work.
回答2:
The problem is you're doing integer arithmetic. You need a typecast in order to convert the numerator or denominator to floating point first (e.g.):
int x1 = 2;
int y1 = 4;
int x2 = 11;
int y2 = 7;
double res = (double)(y2-y1)/(x2-x1);
System.out.println(res);
If you do division on whole numbers, the result is truncated to the nearest whole number (which yields the same result as a floor operation). For example:
0 / 2 == 0
1 / 2 == 0
2 / 2 == 1
3 / 2 == 1
etc.
回答3:
try
int x1 = 2;
int y1 = 4;
int x2 = 11;
int y2 = 7;
double res = (double)(y2-y1)/(x2-x1);
System.out.println(res);
You have to box it "while" doing the operation, not after
回答4:
cast (y2-y1)/(x2-x1)
to double like below:
int x1 = 2;
int y1 = 4;
int x2 = 11;
int y2 = 7;
double res = (double)(y2-y1)/(x2-x1);
System.out.println(res);
Output: 0.3333333333333333
来源:https://stackoverflow.com/questions/13148977/output-is-zero-when-dividing