因此,对于我的任务,我应该编写一个带有2个无符号参数并输出其产品的函数。
unsigned multiply( unsigned a, unsigned b );
例如,
multiply(3, 4)
应该返回12
问题是,我不允许使用+, - ,/,*或%运算符。我只允许调用函数,并使用++和 - 。
递增/递减我还有另外一个添加2个参数的函数:
unsigned add(unsigned a, unsigned b)
{
if (a > 0)
add(--a, ++b);
else return(b);
}
我可以调用它,以及我需要的任何帮助函数。
我在过去的30分钟里尝试了各种排列,但我无法正确地计算数学;我最接近的是让自己加倍一次,但这不会削减它。有什么想法吗?
编辑:忘了提! for / while循环不允许
答案 0 :(得分:2)
unsigned add(unsigned a, unsigned b){
if (a > 0)
return add(--a, ++b);
else
return b;
}
unsigned multiply( unsigned a, unsigned b ){
if( a > 0)
return add(b, multiply(--a, b));
else
return 0;
}
答案 1 :(得分:1)
{{1}}
当然,如果必须使用递归,这将无效。
答案 2 :(得分:0)
我没有编译它,但我确定它的工作
Sub StandardEntry()
If ActiveCell.Value = "Yes" And ActivCell.Offset(0, -1).Value = "Term 1" And ActiveCell.Offset(0, -2).Value = "CLV 7" Then
CLV7Term1
Else
If ActiveCell.Value = "Yes" And ActiveCell.Offset(0, -1).Value = "Term 2" And ActiveCell.Offset(0, -2).Value = "CLV 7" Then
CLV7Term2
Else
If ActiveCell.Value = "Yes" And ActiveCell.Offset(0, -1).Value = "Term 3" And ActiveCell.Offset(0, -2).Value = "CLV 7" Then
CLV7Term3
Else
If ActiveCell.Value = "Yes" And ActiveCell.Offset(0, -1).Value = "Term 4" And ActiveCell.Offset(0, -2).Value = "CLV 7" Then
CLV7Term4
Else
If ActiveCell.Value = "Yes" And ActiveCell.Offset(0, -1).Value = "Term 1" And ActiveCell.Offset(0, -2).Value = "CLV 8" Then
CLV8Term1
Else
If ActiveCell.Value = "Yes" And ActiveCell.Offset(0, -1).Value = "Term 2" And ActiveCell.Offset(0, -2).Value = "CLV 8" Then
CLV8Term2
Else
If ActiveCell.Value = "Yes" And ActiveCell.Offset(0, -1).Value = "Term 3" And ActiveCell.Offset(0, -2).Value = "CLV 8" Then
CLV8Term3
Else
If ActiveCell.Value = "Yes" And ActiveCell.Offset(0, -1).Value = "Term 4" And ActiveCell.Offset(0, -2).Value = "CLV 8" Then
CLV8Term4
Else
If ActiveCell.Value = "Yes" And ActiveCell.Offset(0, -1).Value = "Term 1" And ActiveCell.Offset(0, -2).Value = "CLV 9" Then
CLV9Term1
Else
If ActiveCell.Value = "Yes" And ActiveCell.Offset(0, -1).Value = "Term 2" And ActiveCell.Offset(0, -2).Value = "CLV 9" Then
CLV9Term2
Else
If ActiveCell.Value = "Yes" And ActiveCell.Offset(0, -1).Value = "Term 3" And ActiveCell.Offset(0, -2).Value = "CLV 9" Then
CLV9Term3
Else
If ActiveCell.Value = "Yes" And ActiveCell.Offset(0, -1).Value = "Term 4" And ActiveCell.Offset(0, -2).Value = "CLV 9" Then
CLV9Term4
End If
End If
End If
End If
End If
End If
End If
End If
End If
End If
End If
End If
End Sub
答案 3 :(得分:0)
这是一个尾递归解决方案,它使用辅助函数和累加器。这与使用嵌套for
循环的解决方案基本相同:
unsigned multiply(unsigned a, unsigned b)
{
return mult_helper(a, b, 0, a);
}
unsigned mult_helper(unsigned a, unsigned b, unsigned acc, unsigned reset)
{
if (b == 0)
return acc;
if (a > 0)
return mult_helper(--a, b, ++acc, reset);
return mult_helper(reset, --b, acc, reset);
}