C语言中strtod()函数的用法详解

函数原型:

#include <stdlib.h>

double strtod(const char *nptr, char **endptr);

C语言及C++中的重要函数。

  名称含义
  strtod(将字符串转换成浮点数

  相关函数

  atoi,atol,strtod,strtol,strtoul
  
  函数说明
  strtod()会扫描参数nptr字符串,跳过前面的空格字符,直到遇上数字或正负符号才开始做转换,到出现非数字或字符串结束时('\0')才结束转换,并将结果返回。
    若endptr不为NULL,则会将遇到不合条件而终止的nptr中的字符指针由endptr传回。参数nptr字符串可包含正负号、小数点或E(e)来表示指数部分。如123.456或123e-2。

  返回值

  返回转换后的 浮点型数。
 

  附加说明

  参考atof()。

范例
#include<stdlib.h>
#include<stdio.h>
void main()
{
char *endptr;
char a[] = "12345.6789";
char b[] = "1234.567qwer";
char c[] = "-232.23e4";
printf( "a=%lf\n", strtod(a,NULL) );
printf( "b=%lf\n", strtod(b,&endptr) );
printf( "endptr=%s\n", endptr );
printf( "c=%lf\n", strtod(c,NULL) );
}
执行结果:
a=12345.678900
b=1234.567000
endptr=qwer
c=-2322300.000000

补充说明:
附类同的atof函数,atof函数是需要确定a是数字类型的字符串;
-------
atof
1. 函数名: atof
功 能: 把字符串转换成浮点数
名字来源:ascii to floating point numbers 的缩写
用 法: double atof(const char *nptr);
 
中文名
atof()
外文名
ascii to floating point numbers
释    义
. 函数名
功 能
 把字符串转换成浮点数
 
#include<stdlib.h>
#include<stdio.h>
int  main()
{
double  d;
char  str[] =  "123.456" ;
d= atof (str);
printf ( "string=%sdouble=%lf\n" ,str,d);
return  0;
}
基本介绍
2. atof(将字串转换成 浮点型数)
 
相关函数  atoiatolstrtodstrtolstrtoul
 
表头文件 #include <stdlib.h>
 
定义函数 double atof(const char *nptr);
 
函数说明 atof()会扫描参数nptr 字符串,跳过前面的空格字符,直到遇上数字或正负符号才开始做转换,而再遇到非数字或字符串结束时('\0')才结束转换,并将结果返回。参数nptr字符串可包含正负号、小数点或E(e)来表示指数部分,如123.456或123e-2。
 
返回值 返回转换后的 浮点型数。
 
附加说明 atof()与使用 strtod(nptr,(char**)NULL)结果相同。
 
范例 /* 将字符串a 与字符串b转换成数字后相加*/
 
#include<stdlib.h>
int  main()
{
char *a= "-100.23" ;
char *b= "200e-2" ;
doublec;
c= atof (a)+ atof (b);
printf (“c=%.2lf\n”,c);
return  0;
}
执行 c=-98.23

猜你喜欢

转载自www.cnblogs.com/zhuruibi/p/9136630.html
今日推荐