第三节 实践例子 Switch的运用等
案例1:实现两个数的四则运算
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
Console.WriteLine("我是一个简单的计算器,可以实现两个整数的加、减、乘、除、取余"); Console.Write("请输入第一个操作数:"); int a = int.Parse(Console.ReadLine()); Console.Write("请输入第二个操作数:"); int b = int.Parse(Console.ReadLine()); Console.Write("请输入运算符(+ - * / %):"); string c=Console.ReadLine(); int d; if (c=="+") { d=a+b; Console.WriteLine("{0}加{1}等于{2}",a,b,d); } else if (c=="-") { d=a-b; Console.WriteLine("{0}减{1}等于{2}", a, b, d); } else if (c == "*") { d = a*b; Console.WriteLine("{0}乘{1}等于{2}", a, b, d); } else if (b == 0) { Console.WriteLine("除数不能为0"); } else { if (c == "/") { d = a / b; Console.WriteLine("{0}除{1}等于{2}", a, b, d); } else if(c=="%") { d = a % b; Console.WriteLine("{0}除{1}取余等于{2}",a,b,d); } } Console.ReadKey();
案例2: 故宫的门票价格
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
Console.Write("请输入你参观故宫的月份:"); int a = int.Parse(Console.ReadLine()); if (a < 0 || a > 12) { Console.WriteLine("您输入的月份错误"); } else if (a >= 4 && a <= 10) { Console.WriteLine("现在是旺季,门票全价为60,学生20元"); } else { Console.WriteLine("现在是淡季,门票全价为45,学生15元"); } Console.ReadKey();
案例3:参观者的类型
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
Console.WriteLine("请输入你属于那类参观者:\n1-1.2米以下儿童\n2-大中小学生\n3-离休人员\n4-老年人\n5-其他"); int a =int.Parse(Console.ReadLine()); switch (a) { case 1: Console.Write("儿童享受半价"); break; case 2: Console.Write("学生享受8折优惠"); break; case 3: Console.Write("离休人员享受7折优惠"); break; case 4: Console.Write("老年人免费"); break; case 5: Console.Write("全价"); break; } Console.ReadKey();
案例4:判断元音字母
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
Console.Write("请输入一个字母:"); string x = Console.ReadLine(); if (!(x == "a" || x == "e" || x == "i" || x == "o" || x == "u")) { Console.Write("输入的字母不是元音字母"); } else { int y; if (x == "a") { y = 1; } else if (x == "e") { y = 2; } else if (x == "i") { y = 3; } else if (x == "o") { y = 4; } else { y = 5; } switch (y) { case 1: Console.WriteLine("a为元音字母!"); break; case 2: Console.WriteLine("e为元音字母!"); break; case 3: Console.WriteLine("i为元音字母!"); break; case 4: Console.WriteLine("o为元音字母!"); break; case 5: Console.WriteLine("u为元音字母!"); break; } } Console.ReadKey();
方法2:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
Console.Write("请输入一个字母:"); char x =char.Parse( Console.ReadLine()); if (!(x == 'a' || x == 'e' || x =='i' || x == 'o' || x == 'u')) { Console.Write("输入的字母不是元音字母"); } else { switch (x) { case 'a': Console.WriteLine("a为元音字母!"); break; case 'e': Console.WriteLine("e为元音字母!"); break; case 'i': Console.WriteLine("i为元音字母!"); break; case 'o': Console.WriteLine("o为元音字母!"); break; case 'u': Console.WriteLine("u为元音字母!"); break; } } Console.ReadKey();