题目:求1+2+…+n,
要求不能使用乘除法、for、while、if、else、switch、case等关键字以及条件判断语句(A?B:C)。
考虑到用递归来解决,要结束递归,就要判断,不能用关键词,我们可以考虑用&&来终止递归。
#include <iostream>
int sum(int n);
int main()
{
using namespace std;
int n=100,m ;
m = sum(n);
cout<<m<<endl;
system("pause");
return 0;
}
int sum(int n)
{
int temp = 0 ;
(!!n)&&(temp=sum(n-1)) ;
return temp + n;
}
本文介绍了一种不使用传统循环或条件判断语句的方法来实现1到n的累加计算。通过巧妙利用C++特性,如逻辑运算符&&及递归调用来达成目的。示例代码展示了如何在限制条件下完成此任务。
1182

被折叠的 条评论
为什么被折叠?



