-
函數原型:
#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
- 釋 義
- . 函數名
- 功 能
- 把字符串轉換成浮點數
程序舉例:
|
1
2
3
4
5
6
7
8
9
10
|
#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(將字串轉換成
浮點型數)
表頭文件 #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轉換成數字后相加*/
|
1
2
3
4
5
6
7
8
9
10
|
#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
