📜  C语言中的strtof函数

📅  最后修改于: 2021-05-26 03:33:16             🧑  作者: Mango

解析C字符串str(假定),将其内容解释为浮点数(根据当前locale),并以浮点数形式返回其值。如果endptr(endpointer)不是null指针,则该函数还会将endptr的值设置为指向该数字之后的第一个字符。

句法:

strtof(const char* str, char **endptr)
Parameters:
str : String object with the representation of floating point number
endptr : Reference to an already allocated object of type char*, 
whose value is set by the function to the next character in str after the numerical value.
This parameter can also be a null pointer, in which case it is not used.
Return Value : On success, the function returns the
 converted floating-point number as a value of type float.
// C code to convert string having
// floating point as its content
// using strtof function
  
#include 
#include  // Header file containing strtof function
  
int main()
{
    // Character array to be parsed
    char array[] = "365.25 7.0";
  
    // Character end pointer
    char* pend;
  
    // f1 variable to store float value
    float f1 = strtof(array, &pend);
  
    // f2 variable to store float value
    float f2 = strtof(pend, NULL);
  
    // Printing parsed float values of f1 and f2
    printf("%.2f\n%.2f\n", f1, f2);
  
    // Performing operation on the values returned
    printf(" One year has %.2f weeks \n", f1 / f2);
  
    return 0;
}

输出:

365.25
7.0
One year has 52.18 weeks
想要从精选的最佳视频中学习和练习问题,请查看《基础知识到高级C的C基础课程》。