- C 標準庫
- C 庫 - 首頁
- C 庫 - <assert.h>
- C 庫 - <complex.h>
- C 庫 - <ctype.h>
- C 庫 - <errno.h>
- C 庫 - <fenv.h>
- C 庫 - <float.h>
- C 庫 - <inttypes.h>
- C 庫 - <iso646.h>
- C 庫 - <limits.h>
- C 庫 - <locale.h>
- C 庫 - <math.h>
- C 庫 - <setjmp.h>
- C 庫 - <signal.h>
- C 庫 - <stdalign.h>
- C 庫 - <stdarg.h>
- C 庫 - <stdbool.h>
- C 庫 - <stddef.h>
- C 庫 - <stdio.h>
- C 庫 - <stdlib.h>
- C 庫 - <string.h>
- C 庫 - <tgmath.h>
- C 庫 - <time.h>
- C 庫 - <wctype.h>
- C 標準庫資源
- C 庫 - 快速指南
- C 庫 - 有用資源
- C 庫 - 討論
- C 程式設計資源
- C 程式設計 - 教程
- C - 有用資源
C 庫 - <tgmath.h>
C 庫 <tgmath.h> 包含標頭檔案 <math.h> 和 <complex.h>,並定義了各種型別的宏。當根據引數(型別)呼叫實數或複數函式時,此函式適用。
它允許計算機程式設計師表達與任何浮點型別(如 float、long、double 和 long double)一起工作的數學運算。我們可以使用單個函式名稱來表示型別,並使程式碼更易於閱讀。
語法
以下是 C 庫標頭檔案 <tgmath.h> 提供的各種內建函式的語法:
pow(var1, var2) Or, fmod(var1, var2) Or, sin(var1, var2) etc.
引數
上述語法使用各種函式,這些函式僅接受兩個引數來表達數學表示式。例如 - 求兩個數字的冪,獲取三角函式值等。var1 和 var2 屬於相同或不同的資料型別。
返回值型別
該函式根據傳遞給宏的引數型別返回。
請確保 <tgmath.h> 簡化了程式碼維護,並藉助型別通用宏使用數學運算。
示例 1
C 庫標頭檔案 <tgmath.h> 演示了函式 fmod(),它接受兩個不同資料型別的引數並計算兩個數字相除的餘數。
#include <tgmath.h>
#include <stdio.h>
int main() {
float f = 3.0f;
double d = 3.0;
// result is of type double
double result = fmod(f, d);
printf("The result of fmod(%f, %f) = %f\n", f, d, result);
return 0;
}
以上程式碼產生以下結果:
The result of fmod(3.000000, 3.000000) = 0.000000
示例 2
以下示例說明了 cabs() 函式的使用,該函式確定複數的絕對值並顯示結果。
#include <tgmath.h>
#include <complex.h>
#include <stdio.h>
int main() {
float complex fc = 3.0f + 4.0f * I;
double complex dc = 3.0 + 4.0 * I;
long double complex ldc = 3.0l + 4.0l * I;
// res_fc is of type float
float res_fc = cabs(fc);
// res_dc is of type double
double res_dc = cabs(dc);
// res_ldc is of type long double
long double res_ldc = cabs(ldc);
printf("cabs(%f + %fi) = %f\n", crealf(fc), cimagf(fc), res_fc);
printf("cabs(%f + %fi) = %f\n", creal(dc), cimag(dc), res_dc);
printf("cabs(%Lf + %Lfi) = %Lf\n", creall(ldc), cimagl(ldc), res_ldc);
return 0;
}
執行上述程式碼後,我們得到以下結果:
cabs(3.000000 + 4.000000i) = 5.000000 cabs(3.000000 + 4.000000i) = 5.000000 cabs(3.000000 + 4.000000i) = 5.000000
示例 3
這裡,我們使用三角函式來表示資料型別的值:float、double 和 long double。
#include <tgmath.h>
#include <stdio.h>
int main() {
float f = 3.0f;
double d = 3.0;
long double ld = 3.0l;
// result_f is of type float
double result_f = sin(f);
// result_d is of type double
double result_d = sin(d);
// result_ld is of type long double
double result_ld = sin(ld);
printf("The value of float [sin(%f)] = %f\n", f, result_f);
printf("The value of double [sin(%f)] = %f\n", d, result_d);
printf("The value of long [double sin(%Lf)] = %f\n", ld, result_ld);
return 0;
}
執行上述程式碼後,我們得到以下結果:
The value of float [sin(3.000000)] = 0.141120 The value of double [sin(3.000000)] = 0.141120 The value of long [double sin(3.000000)] = 0.141120
廣告