简体   繁体   English

不使用*和/运算符将两个浮点数相乘和相除

[英]Multiplying and Dividing two floating point numbers without using * and / operators

I am trying to solve how to multiply and divide two numbers without using * and / operators 我试图解决如何不使用*和/运算符对两个数相乘和相除

I tried using for loops: 我尝试使用for循环:

for(int a = 1; a<=secondnum; a++)
            {
                total = firstnum + total;
            }
            cout << "Total: " << total;


for(b = firstnum; b>=secondnum; b = b-secondnum)
            {
                total = total + 1;
            }
            cout << "Answer: " << total;

However this only works for integers...Is there a way for this to work on floating point values? 但是这仅适用于整数...是否有办法在浮点值上使用?

In the old days (before pocket calculators and the like), logarithm tables were used to turn multiplication and division into a matter of addition and subtraction: 在过去(在袖珍计算器之类之前),对数表用于将乘法和除法转换为加法和减法:

#include <cmath>

double Mult(double a, double b)
{
  return exp(log(a)+log(b));
}
double Div(double a, double b)
{
  return exp(log(a)-log(b));
}

Note this only works for positive numbers, but it is relatively easy to work with absolute values and then give the result the correct sign. 请注意,这仅适用于正数,但是使用绝对值然后将结果赋予正确的符号相对容易。

I actually did this back in high school. 我实际上是在高中时做的。 I wrote a program that could multiply or divide two arbitrarily-long floating point numbers. 我写了一个程序,可以将两个任意长的浮点数相乘或相除。 Basically, I did it the exact same way I would have done it through long multiplication/division. 基本上,我是通过长时间的乘法/除法来完成此操作的。

I kept both values in arrays of decimal digits. 我将两个值都保留在十进制数字数组中。

char firstValue[1024];
char secondValue[1024];

I don't remember if I kept them as ASCII or converted them. 我不记得我是将它们保留为ASCII还是对其进行了转换。 It was 40 years ago, after all. 毕竟是40年前。

Then I worked it out on paper. 然后我把它写在纸上。 Multiply isn't hard, although admittedly I used the * operator to multiply two one-digit values. 乘起来并不难,尽管我承认使用*运算符将两个一位数字值相乘。 But you could implement an integerMultiply method. 但是您可以实现integerMultiply方法。

If you can do it in long hand on paper, you can write an algorithm for it. 如果您可以长期在纸上做,则可以为其编写算法。 But it's way too long for an answer here. 但这对于这里的答案来说太长了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM