#include <math.h>
#include <stdio.h>
int main(void) {
/* Case 1: explicit cast precedence vs integer division */
int sum = 17, count = 5;
int int_div = sum / count;
double mean = (double)sum / count;
double late_cast = (double)(sum / count);
int c1_pass = (int_div == 3 && fabs(mean - 3.4) < 1e-9 && fabs(late_cast - 3.0) < 1e-9);
/* Case 2: integer promotion (char 'c' = 99 promoted to int) */
int i = 17;
char c = 'c';
int promoted_sum = i + c;
int c2_pass = ((int)c == 99 && promoted_sum == 116 && sizeof(c + c) == sizeof(int));
/* Case 3: usual arithmetic conversions to float/double */
float fsum = (float)(i + c);
double mixed = i + 0.5; /* int promoted to double */
int c3_pass = (fabsf(fsum - 116.0f) < 1e-6f && fabs(mixed - 17.5) < 1e-9 && sizeof(i + 0.5) == sizeof(double));
/* Case 4: narrowing cast truncation and logical operator non-conversion */
long big = 300L;
int narrowed = (int)big;
double pi = 3.99;
int truncated = (int)pi;
int logic_res = (0.5 && 2); /* result is int 1, operands evaluated independently */
int c4_pass = (narrowed == 300 && truncated == 3 && logic_res == 1 && sizeof(0.5 && 2) == sizeof(int));
printf("{\n");
printf(" \"runtime\": \"GCC C11 (mstorsjo/llvm-mingw:20260616)\",\n");
printf(" \"cases\": [\n");
printf(" {\"name\": \"explicit_cast_precedence\", \"expected\": \"3|3.4|3.0\", \"actual\": \"%d|%.1f|%.1f\", \"passed\": %s},\n",
int_div, mean, late_cast, c1_pass ? "true" : "false");
printf(" {\"name\": \"integer_promotion\", \"expected\": [99, 116], \"actual\": [%d, %d], \"passed\": %s},\n",
(int)c, promoted_sum, c2_pass ? "true" : "false");
printf(" {\"name\": \"usual_arithmetic_conversion\", \"expected\": \"116.0|17.5\", \"actual\": \"%.1f|%.1f\", \"passed\": %s},\n",
fsum, mixed, c3_pass ? "true" : "false");
printf(" {\"name\": \"narrowing_and_logic_type\", \"expected\": [300, 3, 1], \"actual\": [%d, %d, %d], \"passed\": %s}\n",
narrowed, truncated, logic_res, c4_pass ? "true" : "false");
printf(" ]\n");
printf("}\n");
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-type-casting-lab/explore-type-casting.c
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-type-casting.c,或下载右侧课程工程包。 - 确认本地已准备 本地离线 Docker 容器(mstorsjo/llvm-mingw:20260616,GCC C11 linux/amd64,--network none)。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联63章) · 含当前章节或实例 · mbskycom202612a3210.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a3265.zip