Can anyone suggest me a way to multiply decimal numbers without using multiplication(*) sign. I know it looks like homework thing, but I just want to know how to achieve this. I have already done this for positive and negative integers as below:
int first = 2;
int second =2;
int result = 0;
bool isNegative = false;
if (first < 0)
{
first = Math.Abs(first);
isNegative = true;
}
if (second < 0)
{
second = Math.Abs(second);
isNegative = true;
}
for (int i = 1; i <= second; i++)
{
result += first;
}
if (isNegative)
result = -Math.Abs(result);
Want to multiply this for decimals:
decimal third = 1.1;
decimal fourth = 1.2;
Thanks
By making use of recursion, we can multiply two integers with the given constraints. To multiply x and y, recursively add x y times. Approach: Since we cannot use any of the given symbols, the only way left is to use recursion, with the fact that x is to be added to x y times.
To multiply decimals, first multiply as if there is no decimal. Next, count the number of digits after the decimal in each factor. Finally, put the same number of digits behind the decimal in the product.
No, it's not possible. There is no operator like ** in C unlike unary increment ( ++ ) and decrement ( -- ) operators. You should have try i *= i .
Bit of a cheat, but if the task strictly relates to all forms of multiplication (rather than just the *
operator), then divide by the reciprocal:
var result = first / (1 / (decimal)second);
Just another way ;)
if (second < 0)
{
second = Math.Abs(second);
first = (-1) * first;
}
result = Enumerable.Repeat(first, second).Sum();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With