首页 > 安全资讯 >

C#的条件循环语句实例分享

18-07-27

C 的条件循环语句实例分享。

C#的条件循环语句实例讲解

using System;

namespace FristLearn
{
 class Program
 {
  static void Main(string[] args)
  {
//goto使用(死循环)
//int a = 0;
//goto skip;//跳转到sikp标签
//back: a++;//定义back
//skip: Console.WriteLine(a);//定义sikp标签
//goto back;//跳转到back标签

//if else else if(猜数字)
int b = new Random().Next(1000);//随机一个0~1000的整数
int count = 0;
Console.WriteLine("随机出一个0~1000的整数,请你猜猜看。");
again:
int Input = 0;
bool isInputError = int.TryParse(Console.ReadLine(), out Input);//尝试转换  成功返回ture 并out input值 失败返回 false
if (!isInputError)
 goto again;//单行if可以不加大括号
if (Input < b || Input > b)
{
 //多行if需要加大括号
 Console.WriteLine(Input < b ? "小" : "大"/*三元运算符*/);//进入这个条件语句的只有两种可能  不可能input=ainputa
 count++;
 goto again;
}
else
{
 Console.WriteLine("猜对,共猜{0}次。", count);
}
//switch (段位)
Console.WriteLine("您的段位是:");
switch (count)
{
 case 1:
 case 2:
  Console.WriteLine("王者");
  break;
 case 3:
 case 4:
 case 5:
  Console.WriteLine("钻石");
  break;
 case 6:
 case 7:
 case 8:
  Console.WriteLine("黄金");
  break;
 case 9:
 case 10:
 case 11:
  Console.WriteLine("白银");
  break;
 case 12:
 case 13:
 case 14:
  Console.WriteLine("青铜");
  break;
 default:
  Console.WriteLine("塑料");
  break;
}
//else if(BMI)
//体质指数(BMI)=体重(kg)÷身高^2(m)
while (true)
{
 Console.WriteLine("计算您的BMI指数(注意单位)\n请输入您的体重(kg)");
 double w = 0, h = 0, BMI = 0;
 isInputError = double.TryParse(Console.ReadLine(), out w);//Console.ReadLine()读取玩家输入并换行
 if (!isInputError)
 {
  Console.WriteLine("输入格式有误");
  continue;//跳出本次循环
 }
 Console.WriteLine("请输入您的身高(m):");
 isInputError = double.TryParse(Console.ReadLine(), out h);
 if (!isInputError)
 {
  Console.WriteLine("输入格式有误");
  continue;
 }

 if (w <= 0 || h <= 0)//判断身高体重是否为负值或0
 {
  Console.WriteLine("请输入有效的身高体重");
  continue;
 }
 BMI = w / (h * h);
 if (BMI < 18.5)
 {
  Console.WriteLine("过轻");
 }
 else if (BMI < 23.9)
 {
  Console.WriteLine("正常");
 }
 else if (BMI < 27)
 {
  Console.WriteLine("过重");
 }
 else if (BMI < 32)
 {
  Console.WriteLine("肥胖");
 }
 else
 {
  Console.WriteLine("非常肥胖");
 }
 break;//终止循环
}
//do while 先执行一次在执行循环
int e = 10;
do
{
 e--;
 Console.WriteLine(e);
} while (e > 1);
//死循环--for
for (; ; )
 {
  break;//终止循环
  //return;//终止循环 并跳出方法
 }
//打印乘法口诀表
for (int i = 1; i < 10; i++)
{
 for (int j = 1; j < i + 1; j++)
 {
  Console.Write("{0}*{1}={2}\t", j, i, i * j);//不换行
 }
 Console.WriteLine();//换行
}
  }

 }
}
相关文章
最新文章
热点推荐