C atof()

atof() 函数在 stdlib.h 头文件中定义。它有助于将给定的字符串参数(str)转换为浮点值,即 double 类型。


double atof(const char *str); #where str should be a string

 

atof() 参数: 

atof() 函数接受一个参数。在 C 语言中,stdlib.h 头文件支持类型转换。

参数 描述 必需/可选
str  表示浮点数的字符串 必需

atof() 返回值

atof() 函数的返回值是作为双精度值的浮点数。

输入 返回值
成功 双精度浮点数值
无效转换

atof() 示例

示例 1:C 语言中 atof() 函数的工作原理?


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
   float f;
   char st[20];
   
   strcpy(st, "23333333");
   f = atof(st);
   printf("String is %s, Float value = %f\n", st, f);

   strcpy(st, "Hi how are you");
   f = atof(st);
   printf("String is %s, Float value = %f\n", st, f);

   return(0);
}

输出


String is 23333333, Float value = 23333333.000000
String is Hi how are you, Float value = 0.000000

示例 2:C 语言中 atof() 如何工作?


#include <stdio.h>

int main (){
  char x[10] = "3.14";
    float pi = atof(x);
    printf("pi value is %f\n", pi);
    return 0;
}

输出


pi value is 3.140000