逻辑运算

与运算

  • 与运算&&表示而且。
  • A && B 只有当A和B都会真,结果才会真。
  • A && B 如果A为假,就不会去计算B了,因为只要A为假结果一定为假。

或运算

  • 或运算用||表示。
  • A || B 只要当A和B中有一个为真,结果就为真。
  • A || B 如果A为真,就不会去计算B了,因为只要A为真结果一定为真。

非运算

  • 非运算是一目运算符。
  • !true的结果为false
  • !false的结果为true

Demo

  • 明天我们班的男生和女生去春游

    using System;
    namespace SourceBook
    {
      enum Sex { Male, Female }
      class Program
      {
          static void Main(string[] args)
          {
              Sex sex1 = Sex.Female;
              Sex sex2 = Sex.Male;
              // 注意这里要使用||运算
              Console.WriteLine(sex1 == Sex.Female || sex1 == Sex.Male); // 输出:True
              Console.WriteLine(sex2 == Sex.Female || sex2 == Sex.Male); // 输出:True
          }
      }
    }
    
  • 明天我们班年满18岁的长头发女生去春游

    using System;
    namespace SourceBook
    {
      enum Sex { Male, Female }
      struct Student
      {
        public int Age;
        public double HearLength;
        public Sex StudentSex;
      }
      class Program
      {
          static void Main(string[] args)
          {
              // 学生1
              Student s1 = new Student();
              s1.Age = 18;
              s1.HearLength = 0.8;
              s1.StudentSex = Sex.Female;       
              // 学生2
              Student s2 = new Student();
              s2.Age = 19;
              s2.HearLength = 0.01;
              s2.StudentSex = Sex.Male;
              // 计算是否能去春游
              Console.WriteLine(s1.Age >= 18 && s1.HearLength > 0.3 && s1.StudentSex == Sex.Female); // 输出:True
              Console.WriteLine(s2.Age >= 18 && s2.HearLength > 0.3 && s2.StudentSex == Sex.Female); // 输出:False
          }
      }
    }
    
  • 一个可以按下和抬起的按钮

    // 之前已经定义了变量isPressed表示按钮是否按下
    // bool isPressed = false; 
    // 按下和抬起的按钮
    isPressed = !isPressed;
    
  • 选一个小于3点的数

    int[] data = new int[10] {2, 6, 3, 4, 1, 2, 6, 3, 4, 5};
    int input = Int32.Parse(Console.ReadLine());
    // Console.WriteLine(data[input]<3?"猜对了":"猜错了"); 
    // 如果用户输入一个超出数组个数的编号程序就会崩溃。
    // 因此我们要检查用户的输入是否在合理范围内。
    Console.WriteLine(intput>=0 && input < data.Length && data[input]<3?"猜对了":"猜错了");
    // 这时如果用户输入的数太大,input < data.Length为false了,这时就已经知道运算结果为false,就不会继续执行后面的data[input]<3。
    

results matching ""

    No results matching ""