#include <stdio.h>
#include <tgmath.h>
#include <stdbool.h>
#define TYPE_TAG(expr) _Generic((expr), \
float: 1, \
double: 2, \
long double: 3, \
float complex: 4, \
double complex: 5, \
long double complex: 6, \
default: 0)
int main(void) {
float f = 1.5f;
double d = 2.5;
long double ld = 3.5L;
int tf = TYPE_TAG(sin(f));
int td = TYPE_TAG(sin(d));
int tld = TYPE_TAG(sin(ld));
int tint = TYPE_TAG(sqrt(4));
double s_int = sqrt(4);
bool c1_pass = (tf == 1 && td == 2 && tld == 3 && tint == 2 && fabs(s_int - 2.0) < 1e-12);
double complex z = 1.0 + 2.0 * I;
int tz_sqrt = TYPE_TAG(sqrt(z));
int tz_exp = TYPE_TAG(exp(z));
double complex sz = sqrt(z);
double complex sq_back = sz * sz;
double err = fabs(creal(sq_back) - 1.0) + fabs(cimag(sq_back) - 2.0);
bool c2_pass = (tz_sqrt == 5 && tz_exp == 5 && err < 1e-12);
float pf = pow(2.0f, 3.0f);
double lg = log10(1000.0);
double c_val = ceil(2.3);
double f_val = floor(2.7);
double m_val = fmod(5.5, 2.0);
double a2 = atan2(1.0, 1.0);
bool c3_pass = (
TYPE_TAG(pow(2.0f, 3.0f)) == 1 &&
fabs(pf - 8.0f) < 1e-6f &&
fabs(lg - 3.0) < 1e-12 &&
c_val == 3.0 && f_val == 2.0 && fabs(m_val - 1.5) < 1e-12 &&
fabs(a2 - acos(-1.0) / 4.0) < 1e-12
);
printf(
"{"
"\"runtime\":\"GCC C11 (mstorsjo/llvm-mingw:20260616)\","
"\"cases\":["
"{\"name\":\"tgmath_real_type_dispatch\",\"expected\":\"f=1,d=2,ld=3,int=2\",\"actual\":\"f=%d,d=%d,ld=%d,int=%d\",\"passed\":%s},"
"{\"name\":\"tgmath_complex_dispatch\",\"expected\":\"tsqrt=5,texp=5,ok=1\",\"actual\":\"tsqrt=%d,texp=%d,ok=%d\",\"passed\":%s},"
"{\"name\":\"tgmath_exp_log_rounding\",\"expected\":\"pow=8.0,log10=3.0,ceil=3.0,floor=2.0,fmod=1.5\",\"actual\":\"pow=%.1f,log10=%.1f,ceil=%.1f,floor=%.1f,fmod=%.1f\",\"passed\":%s}"
"]"
"}\n",
tf, td, tld, tint, c1_pass ? "true" : "false",
tz_sqrt, tz_exp, (err < 1e-12) ? 1 : 0, c2_pass ? "true" : "false",
(double)pf, lg, c_val, f_val, m_val, c3_pass ? "true" : "false"
);
return 0;
}
本例需在 本地离线 Docker 容器(mstorsjo/llvm-mingw:20260616,GCC C11 linux/amd64,--network none)。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:本地离线 Docker 容器(mstorsjo/llvm-mingw:20260616,GCC C11 linux/amd64,--network none)。
入口文件:projects/c-standard-library-tgmath-h-lab/explore-standard-library-tgmath-h.c
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-standard-library-tgmath-h.c,或下载右侧课程工程包。 - 确认本地已准备 本地离线 Docker 容器(mstorsjo/llvm-mingw:20260616,GCC C11 linux/amd64,--network none)。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a3259.zip
课程关联工程包(登记关联63章) · 含当前章节或实例 · mbskycom202612a3210.zip