zoukankan      html  css  js  c++  java
  • (运算符)?: 运算符

      条件运算符 (?:) 根据 Boolean 表达式的值返回两个值之一。 下面是条件运算符的语法。

      condition ? first_expression : second_expression;

      备注

      condition 的计算结果必须为 true 或 false。 如果 condition 为 true,则将计算 first_expression 并使其成为结果。 如果 condition 为 false,则将计算 second_expression 并使其成为结果。 只计算两个表达式之一。

      first_expression 和 second_expression 的类型必须相同,或者必须存在从一种类型到另一种类型的隐式转换。

      你可通过使用条件运算符表达可能更确切地要求 if-else 构造的计算。 例如,以下代码首先使用 if 语句,然后使用条件运算符将整数分类为正整数或负整数。

      int input = Convert.ToInt32(Console.ReadLine());
      string classify;
    
      // if-else construction.
      if (input > 0)
          classify = "positive";
      else
          classify = "negative";
    
      // ?: conditional operator.
      classify = (input > 0) ? "positive" : "negative";

      条件运算符为右联运算符。 表达式 a ? b : c ? d : e 作为 a ? b : (c ? d : e) 而非 (a ? b : c) ? d : e 进行计算。

      无法重载条件运算符。

      示例

      
     1 class ConditionalOp
     2 {
     3     static double sinc(double x)
     4     {
     5         return x != 0.0 ? Math.Sin(x) / x : 1.0;
     6     }
     7 
     8     static void Main()
     9     {
    10         Console.WriteLine(sinc(0.2));
    11         Console.WriteLine(sinc(0.1));
    12         Console.WriteLine(sinc(0.0));
    13     }
    14 }
    15 /*
    16 Output:
    17 0.993346653975306
    18 0.998334166468282
    19 1
    20 */
    View Code
  • 相关阅读:
    【spring 注解驱动开发】spring ioc 原理
    目录大纲,欢迎来戳
    进程相关
    网络编程相关知识点
    Django基本知识
    浅谈 Web框架
    浅谈 Flask 框架
    AJAX小示例
    浅谈cookie 和 session
    ORM:对象关系映射
  • 原文地址:https://www.cnblogs.com/gamerLin/p/4446688.html
Copyright © 2011-2022 走看看