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)进行递归调用。
Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.
示例
#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