任何人都可以建议我一种方法来乘以十进制数而不使用乘法(*)符号.我知道它看起来像家庭作业,但我只是想知道如何实现这一目标.我已经为正负整数做了这个,如下所示:
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);
Run Code Online (Sandbox Code Playgroud)
想要将其乘以小数:
decimal third = 1.1;
decimal fourth = 1.2;
Run Code Online (Sandbox Code Playgroud)
谢谢
Jon*_*ton 12
有点作弊,但如果任务严格涉及所有形式的乘法(而不仅仅是*运算符),则除以倒数:
var result = first / (1 / (decimal)second);
Run Code Online (Sandbox Code Playgroud)
只是另一种方式;)
if (second < 0)
{
second = Math.Abs(second);
first = (-1) * first;
}
result = Enumerable.Repeat(first, second).Sum();
Run Code Online (Sandbox Code Playgroud)