以下代码在int
上运行准确public class Example {
public static void main(String[] args) {
int a = 3, b = 3, mul = 0;
// mul = a * b //this should not be used
for (int i = 1; i <= a; i++)
mul = mul + b;
System.out.println(a + "*" + b + "-->" + mul);
}
}
输出: 3 * 3 - &GT; 9 现在这很完美
但是当我使用双倍时:
public class Example {
public static void main(String[] args) {
double a = 3.5, b = 3.5, mul = 0;
// mul = a * b //this should not be used
for (int i = 1; i <= a; i++)
mul = mul + b;
System.out.println(a + "*" + b + "-->" + mul);
}
}
输出:
3.5 * 3.5 - &GT; 10.5 现在这是错误的,因为
的正确答案3.5 * 3.5 - &GT; 12.25
问题是我需要乘以十进制值,因为循环不支持迭代超过双值。
答案 0 :(得分:3)
计算小数位数,将数字转换为整数,通过加法与循环相乘,然后重新插入小数位。
3.5 x 3.5变为35 x 35,然后小数点向左移动2位,以便给出答案。
答案 1 :(得分:0)
此帖中解释了此类行为 - Java Double Multiplication explanation?
要解决此类问题,最好使用BigDecimal
。
BigDecimal d1 = new BigDecimal("3.5");
BigDecimal d2 = new BigDecimal("3.5");
BigDecimal result = d1.multiply(d2);
System.out.printf("%s * %s = %s%n", d1, d2, result);
答案 2 :(得分:0)
步骤:
你需要String和StringBuilder。
以下是代码:
double a = 3.5, b = 3.5;
StringBuilder num1 = new StringBuilder(Double.toString(a));
StringBuilder num2 = new StringBuilder(Double.toString(b));
int indexOfDecimalPointFromBeginning_num1 = num1.indexOf(".");
int indexOfDecimalPointFromBeginning_num2 = num2.indexOf(".");
int decimalCounterNum1 = num1.length() - indexOfDecimalPointFromBeginning_num1 - 1;
int decimalCounterNum2 = num2.length() - indexOfDecimalPointFromBeginning_num2 - 1;
int decimalCountForResult = decimalCounterNum1 + decimalCounterNum2;
String num1_withoutDecimal = num1.deleteCharAt(indexOfDecimalPointFromBeginning_num1).toString();
String num2_withoutDecimal = num2.deleteCharAt(indexOfDecimalPointFromBeginning_num2).toString();
int newNum1 = Integer.parseInt(num1_withoutDecimal);
int newNum2 = Integer.parseInt(num2_withoutDecimal);
int tempMul = 0;
for (int i = 1; i <= newNum1; i++) {
tempMul = tempMul + newNum2;
}
StringBuilder finalAnswer = new StringBuilder(Integer.toString(tempMul));
finalAnswer.insert(finalAnswer.length() - decimalCountForResult, ".");
Double finalAnswerInDouble = Double.parseDouble(finalAnswer.toString());
System.out.println(a + "*" + b + " --> " + finalAnswer.toString());
答案 3 :(得分:0)
您可以将十进制值转换为除以0的整数,(0 ..)1。 操作后,您应该除以1(0 ..)。
Ex:3,5 * 3,5 =(3,5 / 0,1)*(3,5 / 0,1)/ 100 = 35 * 35/100 = 12,25
<强>代码; 强>
private double multiplication(double d1, double d2) {
double divDiff1 = 1, divDiff2 = 1;
while (d1 != Math.floor(d1)) {
d1 = Double.valueOf(String.format("%.6f", d1 / 0.1));
divDiff1 = divDiff1 / 0.1;
}
while (d2 != Math.floor(d2)) {
d2 = Double.valueOf(String.format("%.6f", d2 / 0.1));
divDiff2 = divDiff2 /0.1;
}
double mul = 0;
for (int i = 1; i <= d1; i++)
mul = mul + d2;
return mul / divDiff2 / divDiff1;
}
如下呼叫;
multiplication(2.5,1.6);