5

谁能建议我一种不使用乘法(*)符号来乘以十进制数的方法。我知道它看起来像家庭作业,但我只想知道如何实现这一点。我已经为正整数和负整数做了这个,如下所示:

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);

想将其乘以小数:

decimal third = 1.1;
decimal fourth = 1.2;

谢谢

4

5 回答 5

12

有点作弊,但如果任务严格涉及所有形式的乘法(而不仅仅是*运算符),那么除以倒数:

var result = first / (1 / (decimal)second);
于 2013-10-01T13:26:18.257 回答
6

只是另一种方式;)

if (second < 0)
{ 
    second = Math.Abs(second);
    first = (-1) * first;
}
result = Enumerable.Repeat(first, second).Sum();
于 2013-10-01T13:26:42.840 回答
2

在不使用 * 运算符的情况下将两个小数相乘的最简单方法是使用 Decimal.Multiply 方法。

例子:

decimal first = -2.234M;
decimal second = 3.14M;

decimal product = Decimal.Multiply(first, second);
于 2013-10-01T13:34:43.353 回答
1

严格没有'*'?我会记下已实现的 XOR 运算符。虽然我知道这段代码与 OP 的代码没有太大区别。

int first = 2;
int second =2;
int result = 0;
bool isNegative;

isNegative = (first<0)^(second<0);

first = (first<0)?Math.Abs(first):first;    
second = (second<0)?Math.Abs(second):second;

for (int i = 1; i <= second; i++)
    result += first;

result = (isNegative)?-Math.Abs(result):result;
于 2013-10-01T13:52:59.187 回答
0

为了完整起见,这是另一种使用日志规则的方法:

decimal result = (decimal)Math.Exp(
    Math.Log((double)third) + Math.Log((double)fourth));

它不适用于所有小数(特别是不适用于负数,尽管它可以扩展以检测并解决它们),但它仍然很有趣。

于 2013-10-01T21:52:34.213 回答