C語言小演算法_1_數值轉換

來源:互聯網
上載者:User
 1 /*
2 StrToInt: 將字串轉換為整型數
3 */
4
5 #include <stdio.h>
6
7 unsigned long int str_to_int(const char *source);
8
9 int main(int argc,char *argv[])
10 {
11 char str[5]="1234";
12 unsigned long int test;
13
14 test=str_to_int(str);
15 printf("%d\n",test);
16
17 return 0;
18 }
19
20 /*
21 函數功能:
22 將一個以0-9字元組成的字串轉換為整型資料
23 函數原型:
24 unsigned long int str_to_int(const char *source)
25 函數參數:
26 char *source: 儲存字串的首地址
27 傳回值:
28 轉換後的Int數值
29 異常:
30 傳遞null 指標或者時函數無法返回正確值
31
32 */
33 unsigned long int str_to_int(const char *source)
34 {
35 unsigned long int result=0;
36
37 while('\0'!= *source )
38 {
39 result =(*source + result - '0')*10;
40 ++source;
41 }
42
43 return result/10;
44 }

 

Exp2:

 1 /*
2 IntToStr: 將整型資料轉換為字串
3 */
4
5 #include <stdio.h>
6
7
8 void int_to_str(const unsigned long int i_number, char *str);
9
10 int main(int argc,char*argv[])
11 {
12 unsigned long int i_test;
13 char str[16];
14
15 i_test=1234567;
16 int_to_str(i_test,str);
17
18 puts(str);
19
20 return 0;
21 }
22
23 /*
24 函數功能:
25 將一個整型數字轉換為一個以0-9的字元組成的字串
26 例如:
27 將 123 ——> “123”
28 函數原型:
29 void int_to_str(const unsigned long int i_number, char *str)
30 函數參數:
31 const unsigned long int i_number: 待轉換的整型值
32 char *str:用來儲存轉換後的字串
33 異常:
34 */
35
36 void int_to_str(const unsigned long int i_number, char *str)
37 {
38 unsigned long int i_temp;
39 char *p_char_head;
40 char *p_char_temp;
41 char char_temp;
42
43 i_temp=i_number;
44 p_char_head=str;
45 p_char_temp=str;
46
47 while( 10 < i_temp )
48 {
49 *(p_char_temp++)= (i_temp % 10) + '0';
50 i_temp /= 10;
51 }
52 *(p_char_temp)=i_temp + '0';
53 *(++p_char_temp)= '\0';
54 --p_char_temp;
55
56 while(p_char_temp > p_char_head)
57 {
58 char_temp=*(p_char_temp);
59 *(p_char_temp--)=*(p_char_head);
60 *(p_char_head++)=char_temp;
61 }
62
63 }
相關文章

聯繫我們

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