BY企鵝
C++基礎語法-4
複習
if & else if & else
#include <iostream>
using namespace std;
int main(){
int a = 10;
if(a == 10){
cout << "a = " << a << endl; //a = 10
}
//程式在這停止執行
else if(a == 7){
cout << "a = " << a << endl;
}
else if(a == 5){
cout << "a = " << a << endl;
}
else{
cout << "a = " << a << endl;
}
}bool
#include <iostream>
using namespace std;
int main(){
char b;
cout << "Please input t or f" << endl;
cin >> b;
bool T = true, F = false;
if(b == 't'){
cout << T; //1
}
else if(b == 'f'){
cout << F; //0
}
}邏輯運算子

集合

重複結構
爲什麼需要重複結構?
//題目:輸出1~10的整數
#include <iostream>
using namespace std;
int main(){
cout << 1 << ' ';
cout << 2 << ' ';
cout << 3 << ' ';
cout << 4 << ' ';
cout << 5 << ' ';
cout << 6 << ' ';
cout << 7 << ' ';
cout << 8 << ' ';
cout << 9 << ' ';
cout << 10 << ' ';
cout << endl;
}
重複結構
//題目:輸出1~10的整數
#include <iostream>
using namespace std;
int main(){
for(int i = 1 ; i <= 10 ; i++){
cout << i << ' ';
}
cout << endl;
return 0;
}
for
//題目:輸出1~10的整數
#include <iostream>
using namespace std;
int main(){
for(int i = 1 ; i <= 10 ; i++){
cout << i << ' ';
}
cout << endl;
return 0;
}-
for的概念比較像計數器,通常會在已知要執行幾次的時候使用
-
寫法:
for(初始值 ; 條件式 ; 更動變數){
執行動作;
}
-
常見用法:
for(int i = 0; i < 執行次數; i++){
執行動作;
}
while
-
while的概念比較像不停重複的判斷式,通常在不知道要執行幾次時使用
-
寫法:
while(條件式){
執行動作;
}
//題目:輸出1~10的整數,由大至小輸出
#include <iostream>
using namespace std;
int main(){
int n = 10;
while(n != 0){
cout << n << ' ';
n -= 1;
}
cout << endl;
return 0;
}
for or while?
//題目:請輸出1~n之間除了2和3的倍數的數字,且 0 < n < 2147483647
#include <iostream>
using namespace std;
int main(){
int n;
cin >> n;
for(int i = 1 ; i <= n ; i++){
if(i % 2 == 0 || i % 3 == 0){
continue;
}
cout << i << ' ';
}
cout << endl;
return 0;
}
-
題目:請輸出1~n之間除了2和3的倍數的數字
for or while?
//題目:請設計一個密碼驗證程式,驗證使用者輸入的密碼是否正確
//保證密碼全都由數字組成,且 0 < 密碼 < 2147483647
#include <iostream>
using namespace std;
int main(){
int password, correct = 12345678;
cin >> password;
while(password != correct){
cout << "密碼錯誤,請重新輸入\n";
cin >> password;
}
cout << "密碼正確\n";
return 0;
}for or while?

EOF
-
EOF (End Of File),中文可以是「直到檔案的結尾」的意思
-
若在zj題目中看到類似敘述,代表一次測試中會有多筆測試資料
-
此時我們可以善用while迴圈

EOF
//西元年被4整除且不被100整除,或被400整除者即為閏年
#include <iostream>
using namespace std;
int main(){
int year;
while(cin >> year){
if((year % 4 == 0 && year % 100 != 0) || year % 400 == 0){
cout << "閏年\n";
}
else{
cout << "平年\n";
}
}
return 0;
}EOF

題目(zj)
結束啦~
下次應該就是基礎語法的最後一堂啦!
我們要上陣列(array)
C++基本上就是多練題目就會變強,
各位加油~
學妹記得報秋遊!
C++中午小社第四堂
By d11130110周月蘅
C++中午小社第四堂
- 461