Output is zero when dividing?

情到浓时终转凉″ 提交于 2020-01-15 10:26:49

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!