- C 标准库
- C 库 - 首页
- C 库 - <assert.h>
- C 库 - <complex.h>
- C 库 - <ctype.h>
- C 库 - <errno.h>
- C 库 - <fenv.h>
- C 库 - <float.h>
- C 库 - <inttypes.h>
- C 库 - <iso646.h>
- C 库 - <limits.h>
- C 库 - <locale.h>
- C 库 - <math.h>
- C 库 - <setjmp.h>
- C 库 - <signal.h>
- C 库 - <stdalign.h>
- C 库 - <stdarg.h>
- C 库 - <stdbool.h>
- C 库 - <stddef.h>
- C 库 - <stdio.h>
- C 库 - <stdlib.h>
- C 库 - <string.h>
- C 库 - <tgmath.h>
- C 库 - <time.h>
- C 库 - <wctype.h>
- C 标准库资源
- C 库 - 快速指南
- C 库 - 有用资源
- C 库 - 讨论
C 库 - strtod() 函数
C 的stdlib 库 strtod() 函数用于将字符串 'str' 指向的字符串转换为双精度浮点数。如果 'endptr' 不为 NULL,则指向转换中使用的最后一个字符之后的字符的指针将存储在 'endptr' 引用的位置。
注意:与 atof() 函数相比,strtod() 函数提供了更高的精度并且可以处理更宽范围的值。
语法
以下是 strtod() 函数的 C 库语法 -
double strtod(const char *str, char **endptr)
参数
此函数接受以下参数 -
-
str - 要转换为双精度浮点数的字符串。
-
endptr - 指向字符指针的指针,用于存储指向数字值后第一个字符的指针。
返回值
此函数返回转换后的双精度浮点数。如果输入字符串无效,则返回 0。
示例 1
在此示例中,我们将字符串转换为浮点数,并使用 strtod() 函数提取数字值后的字符。
#include <stdio.h>
#include <stdlib.h>
int main () {
char str[50] = "2024.05 tutorialspoint";
char *ptr;
double res;
// convert into floating point number
res = strtod(str, &ptr);
//display the numeric part
printf("Double value: %f\n", res);
//display the string after number
printf("String after number: %s", ptr);
return(0);
}
输出
以下是输出 -
Double value: 2024.050000 String after number: tutorialspoint
示例 2
让我们创建另一个示例,我们将两个字符串连接起来,然后将结果字符串转换为浮点数,并使用 strtod() 函数提取数字后的字符。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
// Define two strings to concatenate
char str1[] = "2024.05 ";
char str2[] = "tutorialspoint";
char *ptr;
//calculate the length of string first + second
int length = strlen(str1) + strlen(str2) + 1;
// Allocate memory for the concatenated string
char *concatenated = malloc(length);
// check memory allocation if null return 1.
if(concatenated == NULL) {
printf("Memory allocation failed\n");
return 1;
}
// Concatenate str1 and str2
strcpy(concatenated, str1);
strcat(concatenated, str2);
// use the strlen() function
double number = strtod(concatenated, &ptr);
printf("The concatenated string is: %s\n", concatenated);
printf("The double value is: %f\n", number);
printf("String after number: %s", ptr);
// at the last free the alocated memory
free(concatenated);
return 0;
}
输出
以下是输出 -
The concatenated string is: 2024.05 tutorialspoint The double value is: 2024.050000 String after number: tutorialspoint
示例 3
下面的示例使用 strtod() 函数将字符字符串转换为双精度浮点数。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main () {
double res;
char str[20];
char *ptr;
//define a string
strcpy(str, "tutorialspoint");
//use strtod() function
res = strtod(str, &ptr);
printf("String Value = %s\n", str);
printf("Double value = %f\n", res);
printf("Charater after number = %s", ptr);
return(0);
}
输出
以下是输出,在这里我们得到双精度值为 '0',因为字符串值不是有效的浮点字符串。
String Value = tutorialspoint Double value = 0.000000 Charater after number = tutorialspoint
广告