C# 条件语句 if else 、 switch case 及练习题解析
c#語句主要分為:順序語句、選擇語句(分支語句)、循環語句
條件語句: ?if ?else
格式1:
? ?if()
{}
格式2://二選一
? if()
{}
?else
{}
格式3://多選一
if()
{}
else if()
{}
...
else
{}
格式4://嵌套
if ()
{
? if()
? {}
? else
? {}
}
else
{}
switch ?case:
switch()
{
? ? case1:
? ? ***
? ? break;
......
default:
****
break;
}
?
練習題目:
1、輸入學生姓名,輸入考試成績
若是100,恭喜你**,滿分通過
若是80~100,**,你很優秀,繼續保持
若是60~80,**成績良好
若是50~60,**就差一點點,下次一定要及格
若小于50,**你是笨蛋嗎?
Console.Write("請輸入您的姓名:");
string name = Console.ReadLine();
Console.Write("請輸入您的考試成績:");
double s= double.Parse(Console.ReadLine());
if (s >= 0 && s <= 100)
{
if (s == 100)
{
Console.WriteLine("恭喜您"+name+",滿分通過!");
}
else if (s >= 80)
{
Console.WriteLine(name+",您的成績很優秀,繼續保持!");
}
else if(s>=60)
{
Console.WriteLine(name+",您的成績很好!");
}
else if(s>=50)
{
Console.WriteLine(name+"就差一點點,下次爭取及格!");
}
else
{
Console.WriteLine(name+"你是笨蛋嗎?");
}
}
else
{
Console.WriteLine("輸入的成績有誤!");
}
Console.ReadLine();
?
?
2、輸入一個年份,判斷是否是閏年?
Console.Write("請輸入一個年份:");
int year = int.Parse(Console.ReadLine());
if(year>=0&&year<=9999)
{
if ( (year%4==0 && year%100!=0)||year%400==0 )
{
Console.WriteLine(year+"年,是閏年!");
}
else
{
Console.WriteLine (year+"年,不是閏年!");
}
}
else
{
Console.WriteLine("你是火星人嗎?");
}
Console.ReadLine();
3、輸入年月日,判斷格式是否正確?
Console.Write("請輸入年份:");
int year = int.Parse(Console.ReadLine());
if (year >= 0 && year <= 9999)
{
Console.Write("請輸入月份:");
int month = int.Parse(Console.ReadLine());
if(month>=1&&month<=12)
{
Console.Write("請輸入日期:");
int day = int.Parse(Console.ReadLine());
if (day >= 1 && day <= 31)
{
if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12)
{
Console.WriteLine("輸入正確,您輸入的是" + year + month + day);
}
else if (month == 4 || month == 6 || month == 9 || month == 11)
{
if (day <= 30)
{
Console.WriteLine("輸入正確,您輸入的是" + year + month + day);
}
else
{
Console.WriteLine("您輸入的日期有誤!");
}
}
else
{
if (day <= 29)
{
if (day <= 28)
{
Console.WriteLine("輸入正確,您輸入的是" + year + month + day);
}
else
{
if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0)
{
Console.WriteLine("輸入正確,您輸入的是" + year + month + day);
}
else
{
Console.WriteLine("您輸入的日期有誤!");
}
}
}
else
{
Console.WriteLine("您輸入的日期有誤!");
}
}
}
else
{
Console.WriteLine("您輸入的日期有誤!");
}
}
else
{
Console.WriteLine("您輸入的月份有誤!");
}
}
else
{
Console.WriteLine("您輸入的年份有誤!");
}
Console.ReadLine();
轉載于:https://www.cnblogs.com/hcx999/p/5695424.html
總結
以上是生活随笔為你收集整理的C# 条件语句 if else 、 switch case 及练习题解析的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 九度 1371 最小的K个数
- 下一篇: POJ 2236 Wireless N