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 + "\t電腦手勢:" + 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();
