C語言 三目運算
功能:為真后可根據條件選擇成立兩個不同的表達式
- 如果表達式1值為真選擇表達式2
- 如果表達式1值為假選擇表達式3
案例

#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <string.h> #include <stdlib.h> #include <math.h> #include <time.h> int main(void) { int a = 10; int b = 20; int c = 30; // 表達式1?表達式2:表達式3 // 如果表達式1值為真選擇表達式2 // 如果表達式1值為假選擇表達式3 // 比較兩個數輸出最大值 printf("最大值為:%d\n", a > b ? a : b); // 比較三個數輸出最大值 printf("最大值為:%d\n", a > b ? (a > c ? a : c) : (b > c ? b : c)); return 0; }

#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <string.h> #include <stdlib.h> #include <math.h> #include <time.h> // 宏定義表達式:MAX傳遞值、通過三目運算做比較 #define MAX(a,b) (a)>(b)?(a):(b) int main(void) { int a = 10; int b = 20; printf("%d\n", MAX(a, b)); return 0; }