C庫 - atof() 函式



C 的stdlibatof() 函式用於將字串轉換為浮點數,並將轉換後的浮點數表示為其對應的雙精度值。

浮點數是一種包含小數部分的整數型別,使用小數點表示。例如,像 10.05 和 5.5005 這樣的數字是浮點數。

語法

以下是 atof() 函式的 C 庫語法:

double atof(const char *str)

引數

此函式接受單個引數:

  • str − 它是一個指向以 null 結尾的字串的指標,表示一個浮點數。

返回值

此函式返回一個與雙精度表示相對應的浮點數。如果輸入字串不是有效的浮點數,則返回 0.0。

示例 1

以下是演示 atof() 函式用法的基本 C 示例。

#include <stdlib.h>
#include <stdio.h>
int main(void)
{
   double res;
   char *str; 
   str = "-1509.10E-10";
   res = atof(str); 
   printf("res = %.4e\n", res);
}

輸出

以下是輸出:

res = -1.5091e-007

示例 2

在這個例子中,我們連線了兩個字串,然後使用 atof() 函式將結果字串轉換為浮點數。

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

int main() {
	
    // Define two strings to concatenate
    char str1[] = "123.456";
    char str2[] = "789";
    
    //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);

    // Convert concatenated string into a floating point number.
    // use the atof() function
    double number = atof(concatenated);

    printf("The concatenated string is: %s\n", concatenated);
    printf("The floating point number is: %f\n", number);

    // at the last free the alocated memory
    free(concatenated);
    return 0;
}

輸出

以下是輸出:

The concatenated string is: 123.456789
The floating point number is: 123.456789

示例 3

以下是另一個示例,我們在這裡將數字字串和字元字串都轉換為浮點數。

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

int main () {
   float res;
   char str[20];
   
   //define a string   
   strcpy(str, "151413.10e");
   
   //convert into float
   //use atof() function
   res = atof(str);
   
   printf("String value = %s\n" , str);
   printf("Float value = %f\n", res);

   strcpy(str, "tutorialspoint.com");
   
   //use atof() function
   res = atof(str);
   printf("String value = %s\n", str);
   printf("Float value = %f\n", res);

   return(0);
}

輸出

以下是輸出:

String value = 151413.10e
Float value = 151413.093750
String value = tutorialspoint.com
Float value = 0.000000
廣告
© . All rights reserved.