练习1:循环录入5个人的年龄并计算平均年龄,如果录入的数据出现负数或大于100的数,立即停止输入并报错.
练习2:在while中用break实现要求用户一直输入用户名和密码,只要不是admin、888888就一直提示要求重新输入,如果正确则提登录成功.
练习3:1~100之间的整数相加,得到累加值大于20的当前数
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
![](https://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.gif)
1 int age = 0; 2 int sum = 0; 3 int i = 0; 4 for ( i = 0; i < 5; i++) 5 { 6 Console.WriteLine("请输入第{0}人的年龄?",i+1); 7 try 8 { 9 age = Convert.ToInt32(Console.ReadLine());//防止用户输入的不是数字,所以用try-catch 10 if (age < 0 || age >= 100) 11 { 12 Console.WriteLine("年龄不合法!"); 13 break; 14 } 15 sum = sum + age; 16 } 17 catch 18 { 19 Console.WriteLine("您输入的年龄错误,error!eXIT!"); 20 break; 21 } 22 } 23 //如果通过break跳出循环,i<5肯定是成立的 24 //如果程序执行到这里,并且推出循环不是由于执行了break引起,那么一定是循环条件不成立了 25 if (i < 5==false)// 26 { 27 Console.WriteLine("你输入的5个人的平均年龄为{0}", sum / 5); 28 } 29 30 Console.ReadKey(); 31 }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
![](https://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.gif)
1 string userName, password; 2 while (true) 3 { 4 Console.WriteLine("请输入用户名?"); 5 userName = Console.ReadLine(); 6 Console.WriteLine("请输入密码?"); 7 password = Console.ReadLine(); 8 if (userName == "admin" && password == "888888") 9 { 10 break; 11 } 12 Console.WriteLine("你输入用户名或密码错误,请重新输入!"); 13 } 14 Console.WriteLine("登录成功"); 15 16 Console.ReadKey();
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
![](https://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.gif)
1 int sum = 0; 2 int i = 0; 3 for (i = 1; i <= 100; i++) 4 { 5 sum += i; 6 if (sum >= 20) 7 { 8 break; 9 } 10 11 } 12 Console.WriteLine(i); 13 Console.ReadKey();