我必须制作一个没有*
or/
运算符的乘法函数。我已经做了一个这样的方法。
for(int i=0; i < number1; i++){
result += number2;
}
System.Out.println(result);
现在,这是我的问题:在我的讲师改变话题之前很好,乘法方法必须是可以乘十进制值。我不知道如何制作可以仅使用+
and-
运算符处理十进制值的乘法方法。
我必须制作一个没有*
or/
运算符的乘法函数。我已经做了一个这样的方法。
for(int i=0; i < number1; i++){
result += number2;
}
System.Out.println(result);
现在,这是我的问题:在我的讲师改变话题之前很好,乘法方法必须是可以乘十进制值。我不知道如何制作可以仅使用+
and-
运算符处理十进制值的乘法方法。
是的,您可以使用对数进行乘法运算。
对数(a*b)=对数(a)+对数(b)
然后找出log(a)+log(b)的指数值
然后你可以转换标志..
例如:
-9*8=-72
对数(9*8)=对数(9)+对数(8)=2.19+2.07=4.27
e^4.27=72
现在只有一个 -ve no。然后是-72
否则是 72
我正在编写以下功能:
void multiply(int num1,int num2)
{
int counter=0;
if(num1<0)
{counter++;num1+=num1+num1;}
if(num2<0)
{counter++;num2+=num2+num2;}
double res=Math.log(num1)+Math.log(num2);
int result=(int)Math.exp(res);
if(counter%2==0)
System.out.println("the result is:"+result);
else
System.out.println("the result is:-"+result);
}
希望对你有帮助....
您取小数并逐步移动小数点,直到剩下一个 int:0.041 -> 1. step 0.41 -> 2. step 4.1 -> 3. step 41
乘以 0.041 * 3 可以通过执行上述步骤 3 次,乘以 41 * 3 = 123 来完成。对于结果,您采用 123 并取消步骤:1. 12.3、2. 1.23、3. 0.123。你的结果是:0.123 = 0.041 * 3。
编辑:要确定每个数字的小数位数,您可能会在这个问题中找到答案:How many decimal Places in A Double (Java)
答案在其他人中显示了两种很容易解决此问题的方法:将数字放入字符串并检查该字符串中“.”-DecimalPoint 出现的位置,或使用具有 scale() 方法的 BigDecimal 类型返回小数位数.
这种方法可能更容易理解。您必须添加a
b
时间,或者等效地,b
a
时间。此外,您需要处理 4 种不同的情况,其中a
和b
可以是正数或负数。
public int multiply(int a, int b){
int result = 0;
if (a < 0 && b < 0){
for (int i = a; i <= -1; i++)
result-=b;
}
else if (a < 0){
for (int i = 1; i <= b; i++)
result+=a;
}
else if (b < 0){
for (int i = 1; i <= a; i++)
result+=b;
}
else {
for (int i = 1; i <= b; i++)
result+=a;
}
return result;
}
public static void main(String[] args){
System.out.println(multiply(3,-13)); // -39
}
你不应该期望整个完美的代码:但这里有一个提示来实现这一点。尝试使用recursion
技术而不是for
循环。
public double multiplyMe(double x, double y)
{
if(y == 0 || x == 0)
return 0;
if(y > 0 && x > 0 )
return (x + multiplyMe(x, y-1)); // multiply positive
if(y < 0 || x < 0 )
return - multiplyMe(x, -y); // multiply negative
}
使用日志的另一种方法:
10 升职(log10(x) 和 log10(y) 之和)