C 庫 - strtod() 函式



C 的stdlibstrtod() 函式用於將字串 '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
廣告

© . All rights reserved.