条件运算符?:

条件运算符?:在平时的代码编程之中也是常常用到的,学会新的一种编程方式,就功力就越深厚,技能越多越好,多多益善,而条件运算符?:的条件表达式一般是: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语句的便捷方式,文章就介绍到此,如有喜欢,用您一秒钟的时间为我点赞!

 

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