Reputation: 1781
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?
Upvotes: 1
Views: 204
Reputation: 10843
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.
Upvotes: 7
Reputation: 5052
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
Upvotes: 1
Reputation: 46398
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
Upvotes: 0
Reputation: 120
you need to initially define those variables as doubles and it should work.
Upvotes: 1