C語言 三目運算


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;
}
三目運算 使用案例:宏定義三目運算

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM