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);
时间: 2024-10-18 12:11:08