if语句与switch语句混用
if用来判断 switch用来选择执行
0剪刀 1石头 2布
特殊情况:0与2→0>2
法1 if+switch语句
namespace ConsoleApplication15 { class Program { static void Main(string[] args) { while (true) { int x, y; Random r = new Random(); x = r.Next(0, 3); y = r.Next(0, 3); switch (x) { case 0: Console.WriteLine("X是剪刀"); break; case 1: Console.WriteLine("X是石头"); break; case 2: Console.WriteLine("X是布"); break; } switch (y) { case 0: Console.WriteLine("Y是剪刀"); break; case 1: Console.WriteLine("Y是石头"); break; case 2: Console.WriteLine("Y是布"); break; } Console.WriteLine("X="+x+" Y="+y); if (x==y) { Console.WriteLine("平局"); } else if (x==0&&y==2||x>y) { Console.WriteLine("X获胜"); } else if(x==2&&y==0||x<y) { Console.WriteLine("Y获胜"); } Console.Read(); } } } }
法2
namespace ConsoleApplication1 { class Program { static void Main(string[] args) { while (true) { int x, y, m; Random r = new Random(); x = r.Next(0, 3); y = r.Next(0, 3); m = x - y; Console.Write("x="+x+" y="+y); if( m == -2||m == 1 ) { Console.Write("那就是x赢"); } else if (m ==2|| m ==-1) { Console.Write("那就是y赢"); } else { Console.Write("那就是xy平手"); } Console.ReadLine(); } } } }