C++遞迴程式:列印所有小於N且僅由數字1或3組成的數字
給定一個整數變數N,儲存正整數型別值。任務是遞迴列印所有小於給定值N的數字,這些數字只包含數字1、3或兩者的組合。
讓我們看看這個程式的各種輸入輸出場景:
輸入 - int num = 40
輸出 - 遞迴程式列印所有小於N且僅由數字1或3組成的數字為:33 31 13 11 3 1
說明 - 給定一個儲存在變數num中的正整數40。現在,我們將遞迴查詢所有包含數字1、3或兩者的數字,小於40的數字是1、3、11、13、31、33。
輸入 - int num = 5
輸出 - 遞迴程式列印所有小於N且僅由數字1或3組成的數字為:3 1
說明 - 給定一個儲存在變數num中的正整數5。現在,我們將遞迴查詢所有包含數字1、3或兩者的數字,小於5的數字是1和3。
輸入 - int num = 1
輸出 - 輸入錯誤
說明 - 給定一個儲存在變數num中的正整數1。現在,我們將遞迴查詢所有包含數字1、3或兩者的數字,小於1的正整數只有0,因此輸出“輸入錯誤”。
下面程式中使用的方案如下:
輸入一個整數變數num。透過將num作為引數傳遞給函式Recursive_Numbers(num)。
在函式Recursive_Numbers(num)內部:
宣告一個布林型變數check並將其設定為1。
檢查num是否大於0,如果是則啟動WHILE迴圈,條件是temp大於0且check為1。將digit設定為temp % 10。
檢查digit是否不等於1且digit也不等於3,如果是則將check設定為0。設定temp = temp / 10。
檢查check是否為1,如果是則列印num。
對函式Recursive_Numbers(num - 1)進行遞迴呼叫。
示例
#include <iostream> using namespace std; void Recursive_Numbers(int num){ bool check = 1; int temp = num; if(num > 0){ while(temp > 0 && check == 1){ int digit = temp % 10; if (digit != 1 && digit != 3){ check = 0; } temp = temp / 10; } if(check == 1){ cout<< num << " "; } Recursive_Numbers(num - 1); } } int main(){ int num = 40; if(num <= 1){ cout<<"Wrong input"; } else{ cout<<"Recursive program to print all numbers less than N which consist of digits 1 or 3 only are: "; Recursive_Numbers(num); } return 0; }
輸出
如果我們執行以上程式碼,它將生成以下輸出:
Recursive program to print all numbers less than N which consist of digits 1 or 3 only are: 33 31 13 11 3 1
廣告