練習1:成績等級
寫一程式,運行時向用戶提問「你了多少分?(0-100)」, 接受輸入後判斷其等級並顯示出來:等級={優 90-100;良 80-90;中60-69;差0-59}
- 區間判斷:
if-else if - 定值判斷:
switch-case
if-else if 的寫法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
| static string GetLevel(int score)
{
string level = null;
if (score >= 90) {
level = "優";
} else if (score >= 80) { //不需要寫小於等於90,會走到這裡代表已經是<= 90
level = "良";
} else if (score >= 70) {
level = "中";
} else if (score >= 60) {
level = "差";
} else {
level = "不及格";
}
return level;
}
|
switch-case 的寫法
想辦法把區間變成定值score / 10
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
| static string GetLevel(int score)
{
string level = null;
switch (score / 10)
{
case 10:
case 9: level = "優";
break;
case 8: level = "良";
break;
case 7: level = "中";
break;
case 6: level = "差";
break;
default: level = "不及格";
break;
}
return level;
}
|
執行
1
2
3
4
5
6
7
8
| static void Main(string[] args)
{
Console.WriteLine("請輸入你的考試成績:");
int score = Convert.ToInt32(Console.ReadLine());
string level = GetLevel(score);
Console.WriteLine(level);
Console.ReadKey();
}
|
練習2:99乘法表
1
2
3
4
5
6
7
8
9
| for (int i = 1; i <= 9; i++)
{
for (int j = 1; j <= 9; j++)
{
Console.Write($"{i}x{j}={i*j}\t");
}
Console.WriteLine();
}
Console.ReadKey();
|
練習3:依據用戶的輸入去輸出每一行要顯示幾個數字
定義長度50的數組,隨機給數組賦值,並可以讓用戶輸入一個數字n,每一行輸出n個數組。int[] array = new int[50] Random r = new random(); r.Next();
1
2
3
4
5
6
7
8
9
10
11
12
| 依據用戶的輸入,去輸出每一行要顯示幾個數字後再換行
換行的規律:如果`(索引值+1)%n`剛好等於0就換行
例如:n=10
第一行的最後一個索引值 nums[9] => (9+1)%10=0
第二行的最後一個索引值 nums[19] => (19+1)%10=0
第三行的最後一個索引值 nums[29] => (29+1)%10=0
例如:n=5
第一行的最後一個索引值 nums[4] => (14+1)%5=0
第二行的最後一個索引值 nums[9] => (9+1)%5=0
第三行的最後一個索引值 nums[14] => (14+1)%5=0
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
| static void Main(string[] args)
{
//為陣列隨機賦值
int[] nums = new int[50];
Random r = new Random();
for (int i = 0; i < nums.Length; i++)
{
nums[i] = r.Next(0, 10); //1-9
}
Console.WriteLine("請隨機輸入一個數,會依照你的數字去輸出每一行的個數");
int n = Convert.ToInt32(Console.ReadLine());
//依據用戶的輸入值,去輸出每一行要顯示幾個數字,再換行
for (int i = 0; i < nums.Length; i++)
{
Console.Write(nums[i]+"\t");
//換行的規律:如果(索引+1)%n 剛好等於0就換行
if ((i + 1) % n == 0) Console.WriteLine();
}
Console.ReadKey();
}
|