switch case分支语句
switch(一个变量值)
{
case 值:要执行的代码段;break;
case 值:要执行的代码段;break;
…
default:代码段;break;(default可有可无,对应else)
}
循环语句
for,while,foreach
循环四要素:初始条件,循环条件,循环体,状态改变;
for(初始条件;循环条件;状态改变)
{
循环体;
}
Console.Write("请输入一个100以内的数"); int i = Convert.ToInt32(Console.ReadLine()); int n,sum=0; for (n = 1; n <= i; n++) { sum += n; } Console.WriteLine(sum); Console.ReadLine();
#region
代码
#endregion
可以起到折叠代码的作用;
在代码前输入:Console.ForegroundColor=ConsoleColor.颜色(Red/Blue...);
练习题:
1、打印100以内所有的质数/素数,再求和
int sum = 0; //循环2-100之间所有的数 for (int i = 2; i < 100; i++) { int count = 0; //在这循环查看当前循环的数能被整除几次 for (int j = 1; j <= i; j++) { if (i % j == 0) count++; } //如果被整除2次,说明就是质数 if (count==2) { sum += i; Console.WriteLine(i); } } Console.WriteLine(sum); Console.ReadLine();
2、猜拳(三局两胜)
int u = 0; int c = 0; for (; ; ) { #region 手势生成 Console.Write("请输入您的手势(石头、剪刀、包袱):"); string user = Console.ReadLine(); int user1; if (user == "石头") user1 = 0; else if (user == "剪刀") user1 = 1; else user1 = 2; Random r = new Random(); int com = r.Next(0, 3); #endregion #region 输出两位选手的手势 string comEnd = ""; if (user != "剪刀" && user != "石头") { user = "包袱"; } if (com == 0) comEnd = "石头"; else if (com == 1) comEnd = "剪刀"; else comEnd = "包袱"; Console.WriteLine("用户手势:" + user + " 电脑手势:" + comEnd); #endregion #region 胜负判断 if ((user1 == 0 && com == 1) || (user1 == 1 && com == 2) || (user1 == 2 && com == 0)) { Console.WriteLine("用户胜利!"); u++; } else if ((user1 == 0 && com == 2) || (user1 == 1 && com == 0) || (user1 == 2 && com == 1)) { Console.WriteLine("用户失败!"); c++; } else { Console.WriteLine("平局!"); } #endregion Console.WriteLine(); Console.WriteLine("用户胜利" + u + "局,电脑胜利" + c + "局"); if (u == 2) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("用户获得最终胜利!"); break; } else if (c == 2) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("电脑完成了五杀!"); break; } Console.WriteLine("-----------下一局开始-----------"); } Console.ReadLine();