c語言實現輸出一個數的每一位

來源:互聯網
上載者:User

標籤:pos   warning   依次   obj   第一個   art   方法   --   printf   

比方輸入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;}


註:最後兩段代碼都未引入標頭檔。在每段代碼中。測試資料我都是直接給出,當然,我們也能夠鍵盤輸入測試資料~~

c語言實現輸出一個數的每一位

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.