21、写一个函数,将一个整数的各位数字的反序打印
//写一个函数,将一个整数的各位数字的反序打印
#include<iostream>
#include<stdlib.h>
using namespace std;
//int reverse_out(int n)
//{
// while(n)
// {
// cout << n%10 << " ";
// n /= 10;
// }
// cout << endl;
// return 0;
//}
void show(int n)
{
if(n < 10) cout << n;//递归函数结束条件
else
{
cout << n%10 << " " ;
show(n/10);
}
}
int main()
{
int x;
cin >> x;
//reverse_out(x);
show(x);
system("pause");
return 0;
}
总结
1、函数show()采用递归求解,if(n<10) cout << n;看着多余,实则是递归函数结束条件,不可或缺;
22、写一个函数,将一个整数的各位数字的按顺序打印
//写一个函数,将一个整数的各位数字的按顺序打印
#include<iostream>
#include<stdlib.h>
using namespace std;
//int show_m1(int n)
//{
// int a[10] = {0}, i = 0;
// while(n)
// {
// a[i] = n%10;
// i++;//i多加了一次
// n /= 10;
// }
// for(i; i>0; i--)
// cout << a[i-1] << " ";
// return 0;
//}
void show_m2(int n)
{
if(n < 10) cout << n;//递归函数结束条件
else
{
show_m2(n/10);
cout << " " << n%10;
}
}
int main()
{
int x;
cin >> x;
//show_m1(x);
show_m2(x);
system("pause");
return 0;
}
总结
1、show_m1()采用先求余取得从低位到高位各个位数,放入一个数组再逆序打印,不用考虑是几位数,但需增加数组逆序输出循环;
2、show_m2()采用递归,同21题代码相比只是调换了顺序,解法很妙!!
3、参考代码还有一种方法,用了两个while(),一个先确定几位数,一个取整顺序输出;