C++常考笔试题:不用if,while,do-while,for,打印出所有大于0小于k的整数.函数原型void printLess(int k);

2014-11-24 09:23:23 · 作者: · 浏览: 1

笔试过程中左思右想,除了用定义一个类,利用其构造函数自动执行的特性来实现这个函数的功能,但是我想那样做的话肯定没有达到题目的要求.

回到学校后时不时想一想这个题的解法,终于想出一个解题思路.

解法一:递归方式(刚想出来)

[cpp]
#include
using namespace std;
void printLess(int k){
switch(--k){
case 0:return;
default:
cout << k << endl;
printLess(k);
}
}
int main(){
printLess(10);
}

解法二:类方式

[cpp]
class Test{
public:
static int k;
Test(){
cout << k++ << endl;
}
};
int Test::k = 1;
void _printLess(int k){
Test t[k-1];
}