整數轉換字串

來源:互聯網
上載者:User

標籤:

思路:首先確定整數的長度,這樣做有兩個好處。

  • 一個是用於節省記憶體,因為要事先申請字串地址空間;
  • 一個是長度後,可以直接取整數的高位,不需要從個位取,從個位取構成的字串後面還需要一個逆序

具體代碼如下:

/* *整數轉化成字串*/#include <stdio.h>#include <stdlib.h>#include <math.h>char *IntToString(int a){    int temp=a;//儲存a的值    int len;//緩衝用地    int b=a%10;     int count=0;//計算整數的長度    char *string;    while(b!=0)    {        count++;        a=a/10;        b=a%10;        if(b==a)            break;    }    count++;    string=(char *)malloc(count+1);    b=temp%10;    len=count;    printf("count=%d\n",count);    while(temp)    {        a=temp/Mypow10(--count);        (*string++)=a+‘0‘;        temp=temp-a*Mypow10(count);    }    *string=0;    string=string-len;    return string;}int Mypow10(int a){    if(a<0)        return 0;    int i=1;    int sum=1;    for(i=1;i<=a;i++)    {        sum=sum*10;    }    return sum;}int main(void){    int a=123;    printf("請輸入一個整數:\n");    scanf("%d",&a);    char *b=IntToString(a);    printf("%s\n",b);    return 0;}

 

整數轉換字串

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.