Latest web development tutorials

C 庫函數– atof()

C 標準庫 - <stdlib.h> C標準庫- <stdlib.h>

描述

C庫函數double atof(const char *str)把參數str所指向的字符串轉換為一個浮點數(類型為double型)。

聲明

下面是atof() 函數的聲明。

double atof(const char *str)

參數

  • str --要轉換為浮點數的字符串。

返回值

函數返迴轉換後的雙精度浮點數,如果沒有執行有效的轉換,則返回零(0.0)。

實例

下面的實例演示了atof() 函數的用法。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
   float val;
   char str[20];
   
   strcpy(str, "98993489");
   val = atof(str);
   printf("字符串值 = %s, 浮点值 = %f\n", str, val);

   strcpy(str, "w3cschool.cc");
   val = atof(str);
   printf("字符串值 = %s, 浮点值 = %f\n", str, val);

   return(0);
}

讓我們編譯並運行上面的程序,這將產生以下結果:

字符串值 = 98993489, 浮点值 = 98993488.000000
字符串值 = w3cschool.cc, 浮点值 = 0.000000

C 標準庫 - <stdlib.h> C標準庫- <stdlib.h>