zoukankan      html  css  js  c++  java
  • 1.5 测试奇偶性

    知识点:

    1.奇数偶数判断:(1)与2相除取余(%) (2)与1相与(&)判断是否为0

    2.两个方法体可以写一个,不过写两个增加可读性。

    问题:

    需要一个简单的方法来测试一个数值,以确定它是奇数还是偶数。

    解决方案

     1 using System;
     2 using System.Collections.Generic;
     3 using System.Linq;
     4 using System.Text;
     5 using System.Threading.Tasks;
     6 
     7 namespace _06测试奇偶性
     8 {
     9     class Program
    10     {
    11         static void Main(string[] args)
    12         {
    13             Console.WriteLine("请输入数字:");
    14             var  value= Console.ReadLine();
    15             bool valueProp = IsEven(Convert.ToInt32(value));
    16             if (valueProp)
    17             {
    18                 Console.WriteLine("Is Even");
    19             }
    20             else
    21             {
    22                 Console.WriteLine("Is Odd");
    23             }
    24             Console.ReadKey();
    25         }
    26 
    27         //方法一: 与2相除取余
    28         public static bool IsEven(int intValue)
    29         {
    30             return (intValue % 2 == 0);
    31         }
    32 
    33         public static bool IsOdd(int intValue) 
    34         {
    35             return (intValue % 2 == 1);
    36         }
    37 
    38         //方法二: 奇数总是将其最低位设置为1。因此可以与1相与(AND),如果为0 ,则为偶数,如果为1则为奇数
    39         public static bool IsOdd(int intValue) 
    40         {
    41             return (!IsEven(intValue));
    42         }
    43 
    44         public static bool IsEven(int intValue)
    45         {
    46             return ((intValue & 1) == 0);
    47         }
    48     }
    49 }
    View Code

    验证结果

    1.输入5 ,结果为IsOdd

    2.输入6,结果为IsEven

  • 相关阅读:
    ubuntu安装openssh-server 报依赖错误的解决过程
    LDA(Latent Dirichlet Allocation)主题模型算法
    ajax乱码
    virtualbox安装xp虚拟机缺少驱动
    mysql命令行操作
    hibernate本地验证
    mingw下的msys显示与输入乱码
    msys访问windows其他盘
    LeetCode 364. Nested List Weight Sum II
    LeetCode 535. Encode and Decode TinyURL
  • 原文地址:https://www.cnblogs.com/weijieAndy/p/3990141.html
Copyright © 2011-2022 走看看