比如输入1234,在屏幕上打印出1 2 3 4
代码展示:
方法一:
- #define _CRT_SECURE_NO_WARNINGS 1
- #include<stdio.h>
- #include<math.h>
- //实现打印一个数的每一位
- int main()
- {
- int num = 1234;
- int count = 0;//用来保存数字的位数
- int tmp = num;
- int y = 0;
- while (tmp)
- {
- ++count;
- tmp /= 10;
- }
- while (num)
- {
- printf("%d ",y = num/pow(10,count-1));
- num = num - y * pow(10,count - 1);
- --count;
- }
- system("pause");
- return 0;
- }
分析:对于给定的数或者是输入的数,从高位到低位一次输出~第一个while循环计算出了数据的位数,第2个while循环用于打印每一个位,如果我们没有定义tmp变量,第一个while执行完,给定数字变成0,第二个while就进不去。所以,设定新的变量保存一份数据。
第2个while是如何实现打印的呢?以num = 1234为例。
num = 1234,打印y = 1234/(10^3) = 1; num = num - 1*1000 = 234;count = 4,;
num = 234,打印y = 234/100 = 2;num = num - 2*100 = 34;
num = 34,......
num = 4,......
num = 0,退出循环~
方法二:
- int main()
- {
- char arr[5];
- int num = 1234;
- int i = 0;
- while (num)
- {
- arr[i] = num % 10 + '0';
- num /= 10;
- i++;
- }
- while (i >= 1)
- {
- printf("%c ",arr[i-1]);
- i--;
- }
- system("pause");
- return 0;
- }
分析:利用字符数组存储每一位,比用整型数组存储更节省空间。以num = 1234为例。第一个while
num= 1234,arr[0] = '4';i = 1;
num = 234, arr[1] = '3';i = 2;
num = 34, arr[2] = '2';i = 3;
num = 4, arr[3] = '1';i = 4;
num = 0,退出循环
第2个while循环,arr[3] = arr[4-1];依次输出~
方法三:递归实现
- void print_num(int n)
- {
- if (n > 9)
- print_num(n/10);
- printf("%d ",n % 10);
- }
- int main()
- {
- print_num(1234);
- system("pause");
- return 0;
- }