我是靠谱客的博主 瘦瘦凉面,最近开发中收集的这篇文章主要介绍【C语言】数字字符串转换成这个字符串对应的数字。,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

(1) int ascii_to_integer(char *str)函数实现。

要求:这个字符串参数必须包含一个或者多个数字,函数应该把这些数字转换为整数并且返回这个整数。如果字符串参数包含任何非数字字符,函数就返回零。不必担心算数溢出。

提示:你每发现一个数字,把当前值乘以10,并把这个值和新的数字所代表的值相加。

直接上代码:

#include <stdio.h>
#include <assert.h>
int ascii_to_integer(char *str)
{
int n = 0;
assert(str);
while(*str != '')
{
while(*str >= '0' && *str <= '9')//判断字符串是否全为数字
{
n = n*10 + (*str-'0');
str++;
}
return n;
}
return 0;
}
int main ()
{
char a[] = "12345";
printf("%dn",ascii_to_integer(a));
return 0;
}

讲解:

字符指针减去’0’(对应ASCII值为48),即将其对应的ASCII码值转换为整型。第一次循环*str指向的是字符’1’,其对应的ASCII码值为49,而’0’对应ASCII码值为48,所以运用”*str-‘0’“目的是将字符’1’转换成数字1,后面以此类推。
.
.
.
.
.
.
.

(2)double my_atof(char *str)函数实现。

要求:将一个数字字符串转换成这个字符串对应的数字(包括正浮点数、负浮点数)。

例如:”12.34”返回12.34;”-12.34”返回-12.34

#include <stdio.h>
#include <assert.h>
double my_atof(char *str)
{
double n = 0.0;
double tmp = 10.0;
int flag = 0;
assert(str);
if(*str == '-')
{
flag = 1;
str++;
}
while(*str >= '0' && *str <= '9')
{
n = n*10 + (*str - '0');
str++;
}
if(*str = '.')
{
str++;
while(*str >= '0' && *str <= '9')
{
n = n + (*str -'0')/tmp;;
tmp = tmp * 10;
str++;
}
}
if(flag == 1)
{
n = -n;
}
return n;
}
int main ()
{
char a[] = "12.345678";
char b[] = "-12.345678";
printf("%fn%fn",my_atof(a),my_atof(b));
return 0;
}

直接上图:


.
.
.
.
.
.
.
(3)int my_atoi(char *str)函数实现。

要求:将一个数字字符串转换成该字符串对应的数字(包括正整数、负整数)。

例如:”12”返回12,”-123”返回-123;

#include <stdio.h>
#include <assert.h>
int my_atoi(char *str)
{
int n = 0;
int flag = 0;
assert(str);
if(*str == '-')
{
flag = 1;
str++;
}
while(*str >= '0' && *str <= '9')
{
n = n*10 + (*str - '0');
str++;
}
if(flag == 1)
{
n = -n;
}
return n;
}
int main ()
{
char a[] = "12";
char b[] = "-123";
printf("%dn%dn",my_atoi(a),my_atoi(b));
return 0;
}

.
.
.
.
.
.
以上三个函数的实现功能非常类似,只需掌握其一,其他便不在话下。

最后

以上就是瘦瘦凉面为你收集整理的【C语言】数字字符串转换成这个字符串对应的数字。的全部内容,希望文章能够帮你解决【C语言】数字字符串转换成这个字符串对应的数字。所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(58)

评论列表共有 0 条评论

立即
投稿
返回
顶部