練習:for迴圈輸入5個人的年齡,並計算平均年齡,如果輸入的數據出現負數或大於100的數,立即停止輸入並報錯
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
int sum = 0; //記錄總和
bool b = true;
for (int i = 1; i <= 5; i++)
{
int age;
Console.WriteLine($"請輸入第{i}個人的年紀");
//try-catch包可能會發生錯誤的地方
try
{
age = Convert.ToInt32(Console.ReadLine());
} catch //亂七八糟的輸入
{
b = false;
Console.WriteLine("不正確數字,程式結束");
break; //跳出當前迴圈
}
//數據負數或大於100的
if (age > 100 || age < 0)
{
b = false;
Console.WriteLine("不正確的年齡範圍,程式結束");
break; //跳出當前迴圈
}
sum += age; //年齡累加到總和裡
}
if (b) Console.WriteLine($"5個人的平均年齡是: {sum / 5}");
練習:在while使用break實現要求用戶一直輸入帳號密碼,是admin/8888則登入成功,否則就一直提示並重新輸入
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
while (true)
{
Console.WriteLine("請輸入帳號");
string username = Console.ReadLine();
Console.WriteLine("請輸入密碼");
string password = Console.ReadLine();
if (username == "admin" && password == "8888")
{
Console.WriteLine("登入成功");
break; //跳出當前迴圈
} else {
Console.WriteLine("帳號或密碼錯誤,請重新輸入");
}
}
練習:1-100之間的整數相加,得到累加值大於20的當前數
比如:1+2+3+4+5+6=21, 結果6, sum>=20
1
2
3
4
5
6
7
8
9
10
int sum = 0;
for (int i = 1; i < 100; i++)
{
sum += i;
if (sum >= 20)
{
Console.WriteLine($"加到{i}的時候,總和為{sum},大於20");
break; //跳出當前迴圈
}
}
練習2: 找出100內的所有質數
質數:只能被1和這個數本身整除的數字 2,3,4,5,6,7 7: 7%2 7%3 7%4 7%5 7%6 7%7 7與之前的數字取餘
不要太糾結算法XD
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
for (int i = 2; i <= 100; i++)
{
bool b = true; //記錄是不是質數
for (int j = 2; j < i; j++)
{
//除盡了,說明不是質數,也就沒有再往下取餘的必要了
if (i % j == 0) //本身與它之前的數字取餘
{
b = false; //不是質數
break; //跳出這個迴圈(結束掉離它最近的j 迴圈)
}
}
if (b) {//是質數
Console.WriteLine(i);
}
}
Console.ReadKey();
1不是質數, 2是質數,因為只有1與2可整除該數。 接下來,3亦為質數,因為1與3可整除3,3除以2會餘1。 因此,3為質數。