首页 > 代码库 > 语句(二)

语句(二)

3、switch 语句:

int casezhi = 1;

switch (casezhi)//小括号内是一个数据类型的值
{
case后加空格,之后写上跟上面小括号内对应类型的可能出现的值
case 1:
 Console.WriteLine("case1");
 break;
case 2:
 Console.WriteLine("case2");
 break;
default:
 Console.WriteLine("没有结果");
 break;
}

例:

练习:计算某月某日是今年的第几天。


Console.Write("请输入月份:");
int yue = int.Parse(Console.ReadLine());
Console.Write("请输入日期:");
int day = int.Parse(Console.ReadLine());

int sumday = 0;

switch (yue)
{
case 1:
sumday = day;
break;
case 2:
sumday = day + 31;
break;
case 3:
sumday = day + 31 + 28;
break;
case 4:
sumday = day + 31 + 28 + 31;
break;
case 5:
sumday = day + 31 + 28 + 31 + 30;
break;
case 6:
sumday = day + 31 + 28 + 31 + 30 + 31;
break;
case 7:
sumday = day + 31 + 28 + 31 + 30 + 31 + 30;
break;
case 8:
sumday = day + 31 + 28 + 31 + 30 + 31 + 30 + 31;
break;
case 9:
sumday = day + 31 + 28 + 31 + 30 + 31 + 30 + 31 + 31;
break;
case 10:
sumday = day + 31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30;
break;
case 11:
sumday = day + 31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31;
break;
default:
sumday = day + 31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31 + 30;
break;
}
Console.WriteLine("这是今年的第"+sumday.ToString()+"天");
Console.ReadLine();

4、for语句:for(初始条件;循环条件;状态改变)

{
循环体,执行代码;
}

for (int i = 1; i < 10; i++)
{
 Console.WriteLine(i);
 if (i == 5)
 {
 break;
 }
}
Console.ReadLine();

 

语句(二)