计算从1加到100不使用循环和条件语句。

解决该问题当然可以使用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;
}



  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值