Kathleen Rose
Kathleen Rose

Reputation: 19

Multiplying a decimal value without using * operator in c++

I was asked to create a calculator without using * in multiplication. The calculator must be able to add, subtract and multiply decimal value also.I'm having problems in the multiplication part. If I multiply a whole number I get the correct answer but if I multiply some decimal value, it outputs an incorrect answer. I can't figure out what is wrong with the code.

#include "pch.h"
#include <iostream>

int main()
{
    double num1 = 0, num2 = 0, product = 0, a = 0, b = 0, c = 0, answer = 0, fres = 0, d = 0.01;

    std::cout << "\nEnter two values:\n";
    std::cin >> num1 >> num2;

    while (a < 100) {
        product = product + num2;
        a++;
    }

    while (b < product) {
        fres = fres + num1;
        b++;
    }

    while (c < fres) {
        answer = answer + d;
        c++;
    }
    std::cout << answer;
}

Upvotes: 1

Views: 947

Answers (1)

Bathsheba
Bathsheba

Reputation: 234665

The primary issue is caused by the fact that repeated addition of a floating point type will likely cause the result to "go off": see for yourself by adding 0.1 ten times, for example. So you shouldn't necessarily return the value attained once the loop stops; perhaps the value immediately before that is closer to the result you want. If both arguments are non-integral then multiplication becomes a fair challenge, and the devil in me would look for an alternative that still satisfies the problem constraints:

Note that an alternative way to achieve multiplication which seems to me at least to satisfy the question constraints is to note that

a * b = std::exp(std::log(a) + std::log(b))

and

a / b = std::exp(std::log(a) - std::log(b))

A less facetious approach would be to use an algorithm based on exponentation by squaring, except that you add instead of multiply.

Upvotes: 1

Related Questions