1、for循環最基本運用:小球每次落地後再彈起是以前的4/5,求第5次彈起後的高度
for (int i = 0; i < 5; i++) { high = high*4/5; } Console.WriteLine("球彈起第5次的高度為:{0}",high);
for循環和if語句的嵌套運用:
2、與電腦猜拳,三局兩勝(沒有考慮人出錯拳的情況,主要是先練習for循環的使用)
int sum1 = 0; int sum2 = 0; string ren1; string dn1; for(int i = 0 ;i<3;i++) { Random r = new Random(); int dn = r.Next(3);//插入0,1,2中的一個隨機數字,將其賦給電腦 Console.WriteLine("請輸入你的:0-剪刀,1-石頭,2-布"); int ren = int.Parse(Console.ReadLine()); if (dn - ren == -1 || dn - ren == 2) sum1++; else sum2++; if (ren == 0) ren1 = "剪刀"; else if (ren == 1) ren1 = "石頭"; else ren1 = "布"; if (dn == 0) dn1 = "剪刀"; else if (dn == 1) dn1 = "石頭"; else dn1 = "布"; Console.WriteLine("電腦出{0},你出{1}", dn1,ren1); } if (sum1 > sum2) Console.WriteLine("你贏了"); else if (sum2>sum1) Console.WriteLine("電腦贏了"); else Console.WriteLine("平局");
3、100以內與7相關的數的和
int sum = 0; for (int i = 0; i < 100; i++) { if (i%7==0||i%10==7||i/10==7) sum = sum+i; } Console.WriteLine(sum);
4、求100內的偶數和,奇數和
int ou = 0; int ji = 0; for (int i = 1; i < 101; i++) { if (i % 2 == 0) ou = ou + i; else ji = ji + i; } Console.WriteLine("偶數和為{0},奇數和為{1}", ou, ji);