输出一个整数的每一位

比如输入1234,在屏幕上打印出1 2 3 4

代码展示:

方法一:

  1. #define _CRT_SECURE_NO_WARNINGS 1  
  2. #include<stdio.h>  
  3. #include<math.h>  
  4. //实现打印一个数的每一位  
  5. int main()  
  6. {  
  7.     int num = 1234;  
  8.     int count = 0;//用来保存数字的位数  
  9.     int tmp = num;  
  10.     int y = 0;  
  11.     while (tmp)  
  12.     {  
  13.         ++count;  
  14.         tmp /= 10;  
  15.     }  
  16.     while (num)  
  17.     {  
  18.         printf("%d ",y = num/pow(10,count-1));  
  19.         num = num - y * pow(10,count - 1);  
  20.         --count;  
  21.     }   
  22.     system("pause");  
  23.     return 0;  
  24. }  

分析:对于给定的数或者是输入的数,从高位到低位一次输出~第一个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,退出循环~

方法二:

  1. int main()  
  2. {  
  3.     char arr[5];  
  4.     int num = 1234;  
  5.     int i = 0;  
  6.     while (num)  
  7.     {  
  8.         arr[i] = num % 10 + '0';  
  9.         num /= 10;  
  10.         i++;  
  11.     }  
  12.     while (i >= 1)  
  13.     {  
  14.         printf("%c ",arr[i-1]);  
  15.         i--;  
  16.     }  
  17.     system("pause");  
  18.     return 0;  
  19. }  

分析:利用字符数组存储每一位,比用整型数组存储更节省空间。以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];依次输出~

方法三:递归实现

  1. void print_num(int n)  
  2. {  
  3.     if (n > 9)  
  4.         print_num(n/10);  
  5.     printf("%d ",n % 10);  
  6. }  
  7. int main()  
  8. {  
  9.     print_num(1234);  
  10.     system("pause");  
  11.     return 0;  
  12. }  

猜你喜欢

转载自blog.csdn.net/zhengxinyu666/article/details/80243404