解决该问题当然可以使用n个printf或cout,但这也太浪费体力了,但如果不能让编译器自己生成这么多printf或cout,也许可以吧。
下面的解决分别从递归,宏函数,类以及模板进行解决。
参考链接:http://coolshell.cn/articles/3445.html
http://bbs.csdn.net/topics/360087177
以下源代码
#pragma once
//递归解决,
//递归结束条件:
//当n为零时(由于&&)
//就不会判断后面
//的表达式的结果
int f(int n)
{
int t = 0;
n && (t = f(n - 1) + n);
return t;
}
void test1()
{
cout << f(100) << endl;
}
//递归
//定义一个数组,存放计算值
//和不计算值,计算完毕后
//调用不计算的那个函数
int YesCount(int n);
int NoCount(int n);
typedef int(*fnPtr)(int);
fnPtr dispath[] = { YesCount, NoCount };
int YesCount(int n)
{
static int ret = 0;
ret += n;
dispath[n == 1](n - 1);
return ret;
}
int NoCount(int n)
{
return 0;
}
void test2()
{
cout << YesCount(100) << endl;
}
//宏函数解决每调用一次
//C(x)加10次
#define C(x) x; x; x; x; x; x; x; x; x; x;
void test3()
{
int sum = 0;
int i = 1;
C(C(sum += i++));
cout << sum << endl;
}
//用类解决
//每次构造ret的值都会增加
class Count
{
public:
Count()
{
ret += i++;
}
static int i;
static int ret;
};
int Count::ret = 0;
int Count::i = 1;
void test4()
{
Count c[100];
cout << Count::ret << endl;
}
//用模板(template)解决
//当N变为1的时候,停止。
template <int N>
int Sum()
{
return N + Sum<N - 1>();
}
template<>
int Sum<1>()
{
return 1;
}
void test5()
{
cout << Sum<100>() << endl;
}