当我将2个数字分开以尝试获得类似.90的数字时,我会持续获得1.0或0.0
int number1 = 6517253;
int number2 = 7195629;
double number3 = number1 / number2; //returns 0.0 supposed to be 0.9057239 and I want 0.90
double number4 = number2 / number1; //returns 1.0 supposed to be 1.1040893 and don't really want that one
如果我将double改为float,会做同样的事情。
答案 0 :(得分:7)
您应该将其中一个操作数转换为double
。尝试:
double number3 = (double) number1 / number2;
double number4 = (double) number2 / number1;
这是因为Java将int / int
的类型推断为int
,但double / int
的类型推断为double
。
答案 1 :(得分:0)
将其中一个数字转换为double:
double number3 = number1 / (double) number 2
答案 2 :(得分:0)
java中的文字或整数变量的每个操作都返回一个整数类型(uint32),因此您需要对操作进行类型转换
double number3 = (double)number1/number2;