迴圈與遞迴–不使用if,while,for,do—while語句來輸出所有比已知數N小的自然數

來源:互聯網
上載者:User

不用迴圈的時候,如何用遞迴解決簡單的迴圈問題!

問題:如何不使用if,while,for,do...while語句來輸出所有比已知數N小的自然數。(含0)

     這個問題不是我自己想出來的,只是在一個哥們的部落格中看到的,這哥們解決這問題的方式居然是用彙編寫了個迴圈。不曉得怎麼說他啊。以下是自己在網上搜尋或者自己思考,自己稍加整理的,主要是採用遞迴,考慮到遞迴裡面最終還會涉及到判斷:在不用 if等的情況下,採用了三目運算子。

(1)

#include<iostream>using namespace std;int x=15;int work(int n){cout<< n-1<<endl; return n-1>0 ? work(n-1):0;}int main(void){ return x>0 ? work(x) : 0;}

(2)要終結遞迴,必然涉及判斷,而判斷的實質“真”與“假”(即“1”與“0”).要想判斷最終n與0的

void MyPrint(int n)     /*輸出0---N-1*/{   int flag=1;    pirntf("%d  ",--n);    flag=(n>0);     //此處也可寫為 flag=n-0;    switch(flag)    {     case 1:MyPrint(n);break;     case 0:break;    }}

(3)根據除法的被除數為0時,異常,退出程式。(不推薦使用)

#include <stdio.h>#define  MAX  15int boom;void foo(int n) {    boom = 1 / (MAX-n);    printf("%d\n", n);    foo(n+1);}int  main(void) {    foo(0);    return 0;}

(4)樓下評論一樓
wohaaitinciu
的方法:(表示感謝 )

#include<iostream>using namespace  std;int func(int n){n && func(n - 1);return printf("%d\n", n);}int main(){func(15);return 0;}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.