C++常考笔试题:不用if,while,do-while,for,打印出所有大于0小于k的整数.函数原型void printLess(int k);
解法一:递归方式(刚想出来)
- #include <iostream>
- using namespace std;
- void printLess(int k)
- {
- switch(--k)
- {
- case 0:return;
- default:
- cout << k << endl;
- printLess(k);
- }
- }
- int main()
- {
- printLess(10);
- }
解法二:类方式
- class Test
- {
- public:
- static int k;
- Test()
- {
- cout << k++ << endl;
- }
- };
- int Test::k = 1;
- void _printLess(int k)
- {
- //Test t[k-1];
- for (int i = 0;i<m-1;i++)
{
Test Array;//创建类对象,在对象创建的时候,自动调用构造函数,即完成了自动输出
} - }