简体   繁体   中英

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(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. It was 40 years ago, after all.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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