C#入门(5)枚举和结构类型

    技术2022-05-11  10

    通过个人电话本演示枚举类型与结构类型的用法--枚举和结构类型using System;class ID{ //定义枚举类型 public enum Sex {  male, female };        //注意别忘了这里的分号

     //定义电话本的结构类型 public struct TelBook {  public string name;  public Sex sex;    //性别类型为枚举类型  public string number; }

     //每一行打印一位用户的电话本信息 public static void TelPrint( TelBook Someone ) {  Console.Write( Someone.name + "/t");  Console.Write( Someone.sex + "/t");  Console.Write( Someone.number + "/r/n"); }

     public static void Main() {  TelBook Joey, Rose;   //声明TelBook结构类型两位用户Joey和Rose

      Joey.name= "Joey";   //初始化Joey电话本信息  Joey.sex= Sex.male;  Joey.number = "84113128";

      Rose.name = "Rose";   //初始化Rose电话本信息  Rose.sex = Sex.female;  Rose.number = "84117456";

      TelPrint ( Joey );   //打印两位用户的电话本  TelPrint ( Rose ); }} 

    通过计算n的二阶乘演示跳转控制语句用法//正整数n二阶乘的定义://当n为奇数时,其二阶乘为1*3*5……*n,即1到n之间所有奇数的积//当n为偶数时,其二阶乘为2*4*6……*n,即2到n之间所有偶数的积using System;class Control{ //计算整数n的二阶乘,返回其计算结果 public static long Factorial ( int number ) {  long sum = 1;  for ( int i = 1; i <= number; i++ )  {   if ( number > 20 )   //判断输入数是否太大   {    sum = -1;    break;     //break语句,跳出for循环   }   if ( i % 2 != number % 2 ) //当前数奇偶性于输入数不同时    continue;    //跳出本次循环,进入下一循环   sum = sum * i;  }  return sum;      //终止本方法,返回值sum }

     public static void Main ( ) {  Console.WriteLine("请输入小于等于20的正整数:");  string temp = Console.ReadLine( );  int n = Int32.Parse( temp );  //当输入不合法时提示输入错误  if ( (n <= 0) || ( Factorial ( n ) == -1 ) )   {   Console.WriteLine("输入错误!");   goto Finish;    //跳到标号Finish进行处理  }  //输入合法时,显示其结果  Console.WriteLine("{0} 的二阶乘是: {1}", n, Factorial( n ) ); Finish:  Console.WriteLine("程序结束"); }}

    演示位运算的用法--位运算using System;class BitCal{ public static void Main( ) {  int oper1 = 26;  //二进制为00011010  int oper2 = 52;  //二进制为00110100  //与运算  int AndRes = oper1 & oper2;  Console.WriteLine("26 & 52 = {0}", AndRes);  Console.WriteLine("十六进制显示为:{0:x8}", AndRes);  //或运算  int OrRes = oper1 | oper2;  Console.WriteLine("26 | 52 = {0}", OrRes);  Console.WriteLine("十六进制显示为:{0:x8}", OrRes);  //异或运算  int NotorRes = oper1 ^ oper2;  Console.WriteLine("26 ^ 52 = {0}", NotorRes);  Console.WriteLine("十六进制显示为:{0:x8}", NotorRes);  //取补运算  int NotRes = ~oper1;  Console.WriteLine("~{0} = {1}", oper1, NotRes);  Console.WriteLine("十六进制显示为:{0:x8}", NotRes);  //左移运算:不溢出时,左移n位数值上相当于乘以2的n次方倍  int LeftRes = oper1 << 1;   Console.WriteLine("{0} << 1 = {1}", oper1, LeftRes);  Console.WriteLine("十六进制显示为:{0:x8}", LeftRes);  //右移运算:右移n位数值上相当于除以2的n次方后取整  int RightRes = oper2 >> 3;  Console.WriteLine("{0} >> 3 = {1}", oper2, RightRes);  Console.WriteLine("十六进制显示为:{0:x8}",RightRes ); }}


    最新回复(0)