條件運算符?:

條件運算符?:在平時的代碼編程之中也是常常用到的,學會新的一種編程方式,就功力就越深厚,技能越多越好,多多益善,而條件運算符?:的條件表達式一般是:expression1?expression2:expression3;例如:x = (y < 0) ? -y : y可以這樣簡單的理解,如果y<0的話,則x = -y;否則x = y;代碼表達如下:

if(y < 0)
    x = -y;
else 
    x = y;

那麼下面的話就以一個完整的代碼案例做個說明吧!

#include <stdio.h>
#include <stdlib.h>

/* run this program using the console pauser or add your own getch, system("pause") or input loop */

int main(){
	// 局部變量聲明
   int x, y = 10;
   x = (y < 20) ? 30 : 40;
 
   printf("value of x:%d",x); 
   
   return 0;
}
 

運行結果如下:

代碼案例:

#include <stdio.h>
#include <stdlib.h>

/* run this program using the console pauser or add your own getch, system("pause") or input loop */

int main(){
	// 局部變量聲明
   int x, y = 10;
   x = (y < 10) ? 30 : 40;
 
   printf("value of x:%d",x); 
   
   return 0;
}
 

 運行結果:

 那麼?:使用的意義何在呢?他使用的意義就是if else語句的便捷方式,文章就介紹到此,如有喜歡,用您一秒鐘的時間爲我點贊!

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章