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;//創建類對象,在對象創建的時候,自動調用構造函數,即完成了自動輸出
}? ? - }??