首页 > 其他 > 详细

将数字字符转化为整数

时间:2014-11-24 22:18:03      阅读:476      评论:0      收藏:0      [点我收藏+]

《C和指针》第7章第3道编程题:

为下面这个函数原型编写函数定义:

 int ascii_to_integer( char *string ); 

这个字符串参数必须包含一个或多个数字,函数应该把这些数字字符转换为整数并返回这个整数。如果字符串参数包含了任何非数字字符,函数就返回零。

 1 /*
 2 ** 把数字字符串转化为整数
 3 */
 4 
 5 #include <stdio.h>
 6 
 7 int ascii_to_integer( char *string );
 8 
 9 int 
10 main()
11 {
12     char string[100];
13     gets( string );
14     printf( "%d", ascii_to_integer( string ) );
15     return 0;
16 }
17 
18 /*
19 ** 字符串包含一个或多个数字,函数把数字
20 ** 字符转换为整数,并返回整数。
21 ** 如果字符串中包含非数字字符,函数返回0
22 */
23 int 
24 ascii_to_integer( char *string )
25 {
26     char *sp = string;
27     int result = 0;
28     
29     while( *sp != \0 )
30     {
31         /*
32         ** 如果字符串中包含非数字字符,函数返回0
33         */
34         if( *sp < 0 || *sp > 9 )
35             return 0;
36         /*
37         ** 把当前值乘以10后加上新转化的数字
38         */
39         result = result * 10 + *sp - 0;
40         
41         sp ++;
42     }
43     
44     return result;
45 }

 

将数字字符转化为整数

原文:http://www.cnblogs.com/zouhongmey/p/4119661.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!