C语言小算法_1_数值转换

 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 传递空指针或者时函数无法返回正确值
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 }



原文地址:https://www.cnblogs.com/volcanol/p/2322791.html