# 東華大學資管系初階程式設計112年考古
## 相關資訊
課程代碼:IM__1120AA-初階程式設計
老師:劉英和教授
使用程式:C++
[進階考古](https://hackmd.io/@sumo0711/BkqrQB_SR)
## 免責申明
:::danger
此文件僅為個人參考解答,並非標準答案。請僅供個人學習使用,切勿用於商業用途,如有侵權請寫信告知。
:::
# 初階實習題
## 財務指標
### Description
評估一間公司的存貨流動性可以參考「存貨周轉率」與「存貨周轉天數」這兩個財務指標。請撰寫一支完整的程式,程式當中先後讓使用者輸入一家公司的營業成本、期初存貨與期末存貨(假設皆為帶小數點的數字,單位為萬元),之後再輸出該公司的存貨周轉率與存貨周轉天數 。(讓使用者輸入數值之前請先印出提示字串)
存貨周轉率 = 營業成本 ÷ 平均存貨
平均存貨 = (期初存貨+期末存貨) ÷ 2
存貨周轉天數 = 365天 ÷ 存貨周轉率
### Example
參考執行畫面如下:(粗體字為使用者輸入的)
Please input the cost of sales, beginning inventory, ending inventory.
**100**
**20**
**5**
The inventory turnover is 8
The days sales in inventory is 45.625
### Solution
```cpp=
#include <iostream>
using namespace std;
// operating_cost 營業成本
// beginning_inventory 期初存貨
// ending_inventory 期末存貨
// inventory_turnover 存貨周轉率
// averagez_inventory 平均存貨
// inventory_turnover_days 存貨周轉天數
int main()
{
double operating_cost, beginning_inventory, ending_inventory, inventory_turnover, averagez_inventory, inventory_turnover_days;
cout << "Please input the cost of sales, beginning inventory, ending inventory.\n";
cin >> operating_cost;
cin >> beginning_inventory;
cin >> ending_inventory;
averagez_inventory = (beginning_inventory + ending_inventory) / 2;
inventory_turnover = operating_cost / averagez_inventory;
inventory_turnover_days = 365 / inventory_turnover;
cout << "The inventory turnover is " << inventory_turnover << endl;
cout << "The days sales in inventory is " << inventory_turnover_days;
return 0;
}
```
## 吉尼係數
### Description
吉尼係數(Gini index)為衡量年所得分配公平程度的一個指標。以下圖為例,實際所得分配曲線(紅線)和所得分配絕對平等線(綠線)之間的面積為A,實際所得分配曲線(紅線)和所得分配絕對不平等線(藍線)之間的面積為B,吉尼係數的算法為 A/(A+B)
請撰寫一程式讓使用者輸入A與B的值
接著計算吉尼係數後輸出於螢幕上。
(A與B皆為實數,讓使用者輸入數值之前請先印出提示字串)

### Example
參考執行畫面如下:(粗體字為使用者輸入的)
Please input the areas A and B:
**21.4**
**50.5**
The Gini Index is 0.297636
### Solution
```cpp=
#include <iostream>
using namespace std;
int main()
{
double A, B;
cout << "Please input the areas A and B:\n";
cin >> A >> B;
cout << "The Gini Index is " << A / (A + B);
return 0;
}
```
## BMI
### Description
請撰寫一支完整的程式,程式當中先後讓使用者輸入身高、體重(假設皆為帶小數點的數字),之後再輸出其使用者的BMI值。(讓使用者輸入數值之前請先印出提示字串,請輸出至小數點後兩位。)
BMI = weight / (height * height)
假設使用者輸入的身高單位為公尺,體重單位為公斤。
不用對輸出格式做限制。
### Example
參考執行畫面如下:(粗體字為使用者輸入的)
How tall are you?
**1.81**
How much do you weigh?
**80.0**
Your BMI is 24.42
### Solution
```cpp=
#include <iostream>
#include <iomanip> //setprecision
using namespace std;
int main()
{
double height, weight;
cout << "How tall are you?\n";
cin >> height;
cout << "How much do you weigh?\n";
cin >> weight;
cout << "Your BMI is " << setprecision(4) << weight / (height * height);
return 0;
}
```
## 複利
### Description
請撰寫一支完整的程式以計算數年後的本利和,該程式一開始先讓使用者輸入目前本金多少,再讓使用者輸入欲知多少年後的本利和,接著輸出算得的本利和(輸出至小數點後兩位);假設本金及本利和皆可為帶小數的數字,年利率為2%,採複利計算。
### Example
參考執行畫面如下:(粗體字為使用者輸入的)
How tall are you?
Please input account balance and years to maturity:
**100**
**5**
Your final balance will be 110.41
### Solution
```cpp=
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
double money, years, total = 0, rate = 0.02;
// money 本金 , years 存放年份 , total 當年本金+利息 初始值給 0 ,rate 年利率 0.02
cout << "Please input account balance and years to maturity:\n";
cin >> money >> years;
for (int i = 1; i <= years; i++)
{
total = (1 + rate) * money;
money = total;
}
cout << "Your final balance will be " << setprecision(2) << fixed << total;
return 0;
}
```
## 判斷式
### Description
請撰寫一支完整的程式,該程式一開始請使用者輸入年紀(整數值),隨後依據年紀來輸出問候語:若年紀在0~30間,輸出“哈囉,年輕人!”,不然就輸出“哈囉,成年人!”(讓使用者輸入數值之前,記得先輸出提示語)
### Example
參考執行畫面如下:(粗體字為使用者輸入的)
請輸入你的年紀:
**28**
哈囉,年輕人!
### Solution
```cpp=
#include <iostream>
using namespace std;
int main()
{
int age;
cout << "請輸入你的年紀:\n";
cin >> age;
if (age >= 0 && age <= 30) // age 0~30成立 否則做 else
cout << "哈囉,年輕人!";
else
cout << "哈囉,成年人!";
return 0;
}
```
## TTDI
### Description
世界經濟論壇(WEF)自2022年開始發佈各個國家的旅遊與觀光發展指數(Travel & Tourism DevelopmentIndex, TTDI)以評估各國觀光業的發展與永續經營,其為一大於0的實數。請設計一支程式可以讓使用者輸入若干個國家(國家數量由使用者決定)的國名(一個字串)與 TTDI 值,最後輸出這些國家中 TTDI 值最高的國家其國名與 TTDI 值。
### Example
參考執行畫面如下:(粗體字為使用者輸入的)
Please input how many countries do you have.
**3**
Please input the name and TTDI of each country.
**Japan 5.3**
**USA 5.1**
**Taiwan 5.5**
The country with the highest TTDI is Taiwan and its TTDI is 5.5
### Solution
```cpp=
#include <iostream>
#include <string>
using namespace std;
int main()
{
int num; // 輸入國家數量
string country, max_country; // 國家名稱 最大國家
double ttdi, max_ttdi = 0; // ttdi值 最大 ttdi值 初始為 0
cout << "Please input how many countries do you have:\n";
cin >> num;
cout << "Please input the name and TTDI of each country:\n";
if (num > 0) // 判斷使用者輸入的 num 是否大於 0
{
for (int i = 0; i < num; i++)
{
cin >> country >> ttdi;
if (ttdi > max_ttdi) // 如果當前 ttdi 比 max_ttdi 大進去執行
{
max_ttdi = ttdi; // 將 ttdi 值 input 到 max_ttdi
max_country = country; // 將 country 值 input 到 max_country
}
}
cout << "The country with the highest TTDI is " << max_country << " and its TTDI is " << max_ttdi << endl;
}
else
cout << "Please enter a positive integer." << endl; // 如果使用者輸入小於 0 則印出請輸入正整數
return 0;
}
```
## switch
### Description
請為快樂餐廳撰寫一支點餐程式,程式中會讓使用者輸入欲選擇的套餐代號(代號為一個字母),輸入後,若代號為A(或a),則輸出 good choice,若為B (或b) ,則輸出 wonderful choice,若為C (或c) ,則輸出 excellent choice,若為其他字母,則輸出 wrong input!。(請使用switch,讓使用者輸入數值之前,記得先輸出提示語)
### Example
參考執行畫面如下:(粗體字為使用者輸入的)
Please input your choice: **a**
good choice
Please input your choice: **C**
excellent choice
### Solution
```cpp=
#include <iostream>
#include <string>
using namespace std;
int main()
{
string code;
cout << "Please input your choice:";
cin >> code;
switch (code[0])
{
case 'a':
case 'A':
cout << "good choice";
break;
case 'b':
case 'B':
cout << "wonderful choice";
break;
case 'c':
case 'C':
cout << "excellent choice";
break;
default:
cout << "wrong input!";
break;
}
return 0;
}
```
## 找奇數
### Description
請撰寫一支完整的程式,該程式一開始請使用者輸入一個數字,接著會輸出從1到該數字之間的奇數數字(讓使用者輸入數值之前,記得先輸出提示語,請使用for loop)
### Example
參考執行畫面如下:(粗體字為使用者輸入的)
Please input a number:
**9**
The odd numbers are:
1
3
5
7
9
### Solution
```cpp=
#include <iostream>
using namespace std;
int main()
{
cout << "Please input a number:\n";
int num, odd_num;
cin >> num;
cout << "The odd numbers are:\n";
for (int i = 1; i <= num; i += 2)
// i 初始值為 1 每執行一圈加 2 直到 i 比 num 大就結束
{
odd_num = i;
cout << odd_num << endl;
}
return 0;
}
```
## 巢狀迴圈
### Description
請撰寫一支完整的程式,該程式可讓 3 個使用者各自輸入若干個正整數,每個使用者在輸入若干個正整數後,再輸入一個小於或等於 0 的數字代表輸入結束,每個使用者輸入結束後,會輸出該使用者所輸入的數字(不包含最後那個小於或等於 0 的數字)的總合。(第一層 loop 請使用 for loop,第二層 loop 請使用 do while loop)
### Example
參考執行畫面如下:(粗體字為使用者輸入的)
Please input values:
**2**
**3**
**-1**
The sum is 5
Please input values:
**2**
**-5**
The sum is 2
Please input values:
**3**
**4**
**6**
0
The sum is 13
### Solution
```cpp=
#include <iostream>
using namespace std;
int main()
{
int user_num = 3, input, sum = 0; // 使用者為 3 總和初始值給 0
for (int user = 0; user < user_num; user++)
{
cout << "Please input values:\n";
do
{
cin >> input;
if (input > 0) // 如果使用者輸入大於 0
sum += input;
else
break; // 跳出 do while loop
} while (true); // 無限迴圈
cout << "The sum is " << sum << endl;
sum = 0; // 將總和歸零
}
return 0;
}
```
## cmath
### Description
請撰寫一支完整的程式,該程式一開始請使用者輸入兩個double數字,接著會輸出第一個數字的平方根與第二個數字的絕對值的和(讓使用者輸入數值之前,記得先輸出提示語)
### Example
參考執行畫面如下:(粗體字為使用者輸入的)
Please input two numbers:
**9**
**-5**
The answer is 8
### Solution
```cpp=
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
double num_sqrt, num_fabs;
cout << "Please input two numbers:\n";
cin >> num_sqrt >> num_fabs;
cout << "The answer is " << sqrt(num_sqrt) + fabs(num_fabs);
return 0;
}
```
## Call-By-Value
### Description
請撰寫一支完整程式,程式中有一個function稱為AddFive,其有一個名為Value的int參數,回傳值也是int,在AddFive中,會將Value的值加5之後回傳。在main function中,宣告一個int變數Num,並讓使用者輸入Num的值,隨後呼叫AddFive(將Num當做是參數),之後將AddFive的回傳輸出至螢幕。
### Example
參考執行畫面如下:(粗體字為使用者輸入的)
Please input a value:
**8**
The answer is 13
### Solution
```cpp=
#include <iostream>
using namespace std;
int AddFive(int Value_par);
int main()
{
int Value;
cout << "Please input a value:\n";
cin >> Value;
cout << "The answer is " << AddFive(Value);
return 0;
}
int AddFive(int Value_par)
{
return Value_par + 5;
}
```
## Call-By-Reference
### Description
請撰寫一支完整的程式以計算數年後的本利和,該程式有一function稱為Input,其有一個float參數名為Balance,另有一個int參數名為Term,皆為call-by-reference參數,在Input中會讓使用者輸入Balance與Term的值,兩個變數的值分別代表一開始的本金為多少與欲知多少年後的本利和。另有一function稱為Compute,該function有一個float參數名為Balance,另有一個int參數名為Term,皆為call-by-value參數,該function會計算經過Term這麼多年後的本利和,該function有一float的回傳值,其值為算得的本利和。在main function中連續呼叫Input與Compute以求得本利和並輸出於螢幕上,假設本金及本利和皆可為帶小數的數字,年利率為2%。(採複利計算,請使用for loop,輸出至小數點後兩位)
### Example
參考執行畫面如下:(粗體字為使用者輸入的)
Please input account balance and years to maturity:
**100**
**5**
Your final balance will be 110.41
### Solution
```cpp=
#include <iostream>
#include <iomanip>
using namespace std;
void Input(float &Balance, int &Term);
// 輸入本金及存放年份
float Compute(float Balance, int Term);
// 計算複利
const double RATE = 0.02; // 年利率
int main()
{
float Balance; // Balance 本金
int Term; // Term 存放年份
Input(Balance, Term);
cout << setprecision(2) << fixed << Compute(Balance, Term);
return 0;
}
void Input(float &Balance, int &Term)
{
cout << "Please input account balance and years to maturity:\n";
cin >> Balance >> Term;
return;
}
float Compute(float Balance, int Term)
{
float total = 0; // total 當年本金+利息 初始值給 0
for (int i = 1; i <= Term; i++)
{
total = (1 + RATE) * Balance;
Balance = total;
}
cout << "Your final balance will be ";
return total;
}
```
## function overloading
### Description
請撰寫一支完整的程式,當中包含兩個名稱為ave的function,第一個ave function有兩個double參數,回傳值為double值,其會計算兩個參數的平均值並回傳,第二個ave function有三個double參數,回傳值為double值,其會計算三個參數的平均值並回傳。在main function,會先詢問使用者要輸入幾個數字,若使用者輸入為2,則接著讓使用者輸入兩個實數並使用ave function計算出平均值後輸出於螢幕上,若使用者輸入為3,則接著讓使用者輸入兩個實數並使用ave function計算出平均值後輸出於螢幕上,若使用者輸入的值不為2也不為3,則輸出 wrong input 並結束。
### Example
參考執行畫面如下:(粗體字為使用者輸入的)
How many values you have?
**3**
Please enter three values
**3.2**
**4.2**
**5.1**
The average is 4.16667
### Solution
```cpp=
#include <iostream>
using namespace std;
double ave(double Value1, double Value2);
double ave(double Value1, double Value2, double Value3);
int main()
{
double Value1, Value2, Value3, choose;
cout << "How many values you have?\n";
cin >> choose;
if (choose == 2)
{
cout << "Please enter two values\n";
cin >> Value1 >> Value2;
cout << ave(Value1, Value2);
}
else if (choose == 3)
{
cout << "Please enter three values\n";
cin >> Value1 >> Value2 >> Value3;
cout << ave(Value1, Value2, Value3);
}
else
cout << "wrong input";
return 0;
}
double ave(double Value1, double Value2)
{
cout << "The average is ";
return (Value1 + Value2) / 2;
}
double ave(double Value1, double Value2, double Value3)
{
cout << "The average is ";
return (Value1 + Value2 + Value3) / 3;
}
```
## void function
### Description
請撰寫一支程式計算 b2 – 4 × a × c 的值,該程式的演算法有下列三個步驟:
1.讓使用者輸入變數 a, b, c 的值(皆為整數)
2.計算 b2 – 4 × a × c 的值
3.輸出第二步驟所算得的值於螢幕上
請分別將三個步驟各自寫成一個function,然後在 main function 中呼叫這三個
### Example
參考執行畫面如下:(粗體字為使用者輸入的)
Please input three values:
**5**
**20**
**3**
The result is 340
### Solution
```cpp=
#include <iostream>
using namespace std;
void Input(int &A, int &B, int &C);
int Count(int A, int B, int C);
void Output(int sum);
int main()
{
int a, b, c;
Input(a, b, c);
Output(Count(a, b, c));
return 0;
}
void Input(int &A, int &B, int &C)
{
cout << "Please input three values:\n";
cin >> A >> B >> C;
}
int Count(int A, int B, int C)
{
return B * B - 4 * A * C;
}
void Output(int sum)
{
cout << "The result is " << sum;
}
```
## 檔案輸入輸出
### Description
請撰寫一完整程式,將檔案”infile.txt”中的數字(可能含有自然數,即有小數點的數字)全部讀入(infile.txt中有3個數字),然後求出這些數字的各自的正平方根後,再算出這些正平方根的平均數,最後把下列文字輸出到檔案”outfile.txt”中:
mean: (求得的平均數)
需檢查檔案開啟是否成功
### Example
**infile.txt**
```
4.0
9.0
16.0
25.0
```
**outfile.txt**
```
3.5
```
### Solution
```cpp=
#include <iostream>
#include <fstream>
#include <cmath>
using namespace std;
int main()
{
ifstream infile;
ofstream outfile;
infile.open("infile.txt");
if (infile.fail()) // 如果沒有成功開啟檔案
{
cout << "Input file opening failed.\n";
exit(1);
}
outfile.open("outfile.txt");
if (outfile.fail()) // 如果沒有成功開啟檔案
{
cout << "Output file opening failed.\n";
exit(1);
}
double sum = 0, count = 0, next;
// sum總和 count控制迴圈次數 next文件讀取進來的暫存變數
while (infile >> next) // 條件式用文件輸入 直到文件沒有數值為止
{
next = sqrt(next); // 開根號
sum += next; // 如果是 將文件讀取進來的值加到sum裡
count++;
}
sum = sum / count;
outfile << sum; // 輸出sum到該檔案
infile.close();
outfile.close();
cout << "Success!"; // 執行成功在螢幕輸出提示語
return 0;
}
```
## cctype
### Description
請撰寫一完整程式,程式中開啟檔案input.txt及output.txt,(要檢查檔案是否開啟成功),接著一一讀入input.txt中的內容並輸出至output.txt,但若intpu.txt的內容中有大寫的英文字,輸出至output.txt時就要轉換成小寫,若內容中有小寫的英文字,輸出時就要轉換成大寫。(提示:用isupper、islower檢查讀入的符號是否是大寫或是小寫英文字母。)
### Example
**input.txt**
```
no need to compare with others, just be 1% better than yourself yesterday.
YOU DON’T HAVE TIME TO BE TIMID.
```
**output.txt**
```
NO NEED TO COMPARE WITH OTHERS, JUST BE 1% BETTER THAN YOURSELF YESTERDAY.
you don’t have time to be timid.
```
### Solution
```cpp=
#include <iostream>
#include <fstream>
#include <cctype>
using namespace std;
int main()
{
ifstream infile;
ofstream outfile;
infile.open("input.txt");
if (infile.fail()) // 如果沒有成功開啟檔案
{
cout << "Input file opening failed.\n";
exit(1);
}
outfile.open("output.txt");
if (outfile.fail()) // 如果沒有成功開啟檔案
{
cout << "Output file opening failed.\n";
exit(1);
}
char next;
while (infile.get(next))
{
if (isupper(next)) // 確認是不是大寫
outfile << static_cast<char>(tolower(next));
else if (islower(next)) // 確認是不是小寫
outfile << static_cast<char>(toupper(next));
else if (next == '\n') // 如果是換行,就輸出一個換行給 outfile
outfile << endl;
else
outfile << next; // 不是英文就直接輸出
}
infile.close();
outfile.close();
cout << "Success!";
return 0;
}
```
## eof
### Description
請撰寫一完整程式,程式中開啟檔案input.txt及output.txt,(要檢查檔案是否開啟成功),接著一一讀入input.txt中的內容並輸出至output.txt,但若intpu.txt的內容中有 “C++” 這個字,輸出至output.txt時就只輸出 “C” 即可。
### Example
**input.txt**
```
C++ is a programming language.
I++ is a programming language.
C+ is a programming language.
C is a programming language.
fdaC++elfq+Ckew+p.
```
**output.txt**
```
C is a programming language.
I++ is a programming language.
C+ is a programming language.
C is a programming language.
fdaCelfq+Ckew+p.
```
### Solution
```cpp=
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ifstream infile;
ofstream outfile;
infile.open("input.txt");
if (infile.fail())
{
cout << "Input file opening failed.\n";
exit(1);
}
outfile.open("output.txt");
if (outfile.fail())
{
cout << "Output file opening failed.\n";
exit(1);
}
char next1, next2, next3;
infile.get(next1);
while (!infile.eof()) // 是否被讀完
{
if (next1 != 'C')
outfile << next1;
else
{
infile.get(next2);
infile.get(next3);
if (next2 == '+' && next3 == '+')
outfile << 'C';
else
outfile << next1 << next2 << next3;
}
infile.get(next1);
}
infile.close();
outfile.close();
cout << "Success!";
return 0;
}
```
## array
### Description
請寫一完整程式,當中宣告一個int array變數scores,長度為5,接著讓使用者輸入5個分數分別儲存在scores的5個element中,接著求出這5個分數的平均值、最大值與最小值。(需使用for loop存取各個element,假設使用者輸入的分數均介於0與100之間。提示:可以宣告三個變數分別記錄目前輸入的分數之中的最大值、最小值以及總和,每輸入一個分數就更新這三個變數。)
### Example
參考執行畫面如下:(粗體字為使用者輸入的)
Please input 5 scores:
**10**
**20**
**30**
**40**
**50**
The average is 30
The maximum is 50
The minimum is 10
### Solution
```cpp=
#include <iostream>
using namespace std;
int main()
{
int scores[5], max, min, sum = 0;
cout << "Please input 5 scores:\n";
cin >> scores[0];
max = min = scores[0]; // 用 scores[0] 當 max、min 的初始值
sum += scores[0];
for (int i = 1; i < 5; i++) // 從 scores[1] 開始
{
cin >> scores[i];
if (max < scores[i])
max = scores[i];
if (min > scores[i])
min = scores[i];
sum += scores[i];
}
cout << "The average is " << sum / 5.0 << endl;
cout << "The maximum is " << max << endl;
cout << "The minimum is " << min;
return 0;
}
```
## array function
### Description
請寫一完整程式,其中包含一個function為:void convert(int a[], int size)
在convert中,會使用for loop把 a 的每個element 值加 5。
在main function中,先宣告一大小為 3 的int array變數score,接著使用for loop讓使用者輸入score的 3 個element的值,接著呼叫convert function,並把score及其大小 3 當做參數傳給convert,最後再使用for loop輸出score的 3 個element的值於螢幕上。(程式輸入、輸出資料前,請先輸出提示字串)
### Example
參考執行畫面如下:(粗體字為使用者輸入的)
Please input 3 scores:
**3**
**10**
**20**
After adding 5
**8**
**15**
**25**
### Solution
```cpp=
#include <iostream>
using namespace std;
void convert(int a[], int size);
int main()
{
const int size = 3; // scores array 長度
int scores[size];
cout << "Please input 3 scores:\n";
for (int i = 0; i < size; i++)
cin >> scores[i];
convert(scores, size);
cout << "After adding 5\n";
for (int i = 0; i < size; i++)
cout << scores[i] << " ";
return 0;
}
void convert(int a[], int size)
{
for (int i = 0; i < size; i++)
a[i] += 5;
}
```
## Multidimesional Arrays
### Description
請寫一完整程式,main function中宣告一個兩個維度的int array變數score,兩個維度的長度分別為3與2,score要記錄三個學生各兩個科目的小考成績,接著讓使用者輸入這總共6個成績,然後計算出每個學生的平均成績並輸出。
### Example
參考執行畫面如下:(粗體字為使用者輸入的)
Please input the scores of the student #1:
course #1 :**100**
course #2 :**90**
Please input the scores of the student #2:
course #1 :**85**
course #2 :**95**
Please input the scores of the student #3:
course #1 :**96**
course #2 :**75**
The average of the student #1 is 95
The average of the student #2 is 90
The average of the student #3 is 85.5
### Solution
```cpp=
#include <iostream>
using namespace std;
double average(int a[][2], int student);
int main()
{
int scores[3][2];
for (int i = 0; i < 3; i++)
{
cout << "Please input the scores of the student #" << i + 1 << ":\n";
for (int g = 0; g < 2; g++)
{
cout << "course #" << g + 1 << ": ";
cin >> scores[i][g];
}
}
for (int i = 0; i < 3; i++)
cout << "The average of the student #" << i + 1 << " is " << average(scores, i) << endl;
return 0;
}
double average(int a[][2], int student)
{
double sum = 0;
for (int i = 0; i < 2; i++)
sum += a[student][i];
return sum / 2.0;
}
```
## 陣列不一定要填滿
### Description
請寫一完整程式,該程式可讓使用者輸入最多20個大於或等於0的實數值,若輸入小於0的值代表輸入完畢。請以一個一維陣列儲存所輸入的值。當使用者輸入完畢後,請計算所有輸入值的平方根,再將所有的平方根相加後輸出於螢幕上。
### Example
參考執行畫面如下:(粗體字為使用者輸入的)
Please enter up to 20 real values, a negative value ends the input:
**4**
**9**
**16**
**-1**
The answer is 9
### Solution
```cpp=
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
double scores[20], sum = 0;
cout << "Please enter up to 20 real values, a negative value ends the input:\n";
for (int i = 0; i < 20; i++)
{
cin >> scores[i];
if (scores[i] < 0)
break;
sum += sqrt(scores[i]);
}
cout << "The answer is " << sum;
return 0;
}
```
# 初階回家作業
## 1st homework
### Description
請寫一個完整的程式來實作九九乘法表。 輸出應遵循以下範例:(提示:使用巢狀 for 迴圈)
### Example
**output**
```
1X1=1 1X2=2 1X3=3 1X4=4 1X5=5 1X6=6 1X7=7 1X8=8 1X9=9
2X1=2 2X2=4 2X3=6 2X4=8 2X5=10 2X6=12 2X7=14 2X8=16 2X9=18
3X1=3 3X2=6 3X3=9 3X4=12 3X5=15 3X6=18 3X7=21 3X8=24 3X9=27
4X1=4 4X2=8 4X3=12 4X4=16 4X5=20 4X6=24 4X7=28 4X8=32 4X9=36
5X1=5 5X2=10 5X3=15 5X4=20 5X5=25 5X6=30 5X7=35 5X8=40 5X9=45
6X1=6 6X2=12 6X3=18 6X4=24 6X5=30 6X6=36 6X7=42 6X8=48 6X9=54
7X1=7 7X2=14 7X3=21 7X4=28 7X5=35 7X6=42 7X7=49 7X8=56 7X9=63
8X1=8 8X2=16 8X3=24 8X4=32 8X5=40 8X6=48 8X7=56 8X8=64 8X9=72
9X1=9 9X2=18 9X3=27 9X4=36 9X5=45 9X6=54 9X7=63 9X8=72 9X9=81
```
### Solution
```cpp=
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
for (int G = 1; G <= 9; G++) // G控制第一個數字
{
for (int i = 1; i <= 9; i++) // i 控制第二個數字
cout << G << "X" << i << "=" << G * i << ((G * i < 10) ? " " : " ");
// 三元運算符 協助縮排 使其Output變得好看
cout << endl;
}
return 0;
}
```
## 2nd homework
### Description
寫一個函數 Average,它接受兩個 int 形式參數,並傳回一個 double 值,該值是兩個形式參數的平均值(平均值可以是小數)。 在main函數中,使用者必須輸入三種int類型的值。 然後將較小的兩個值作為呼叫函數 Average 的參數。 然後,將返回值輸出到螢幕。
### Example
參考執行畫面如下:(粗體字為使用者輸入的)
Please enter three integers:
**10**
**7**
**5**
The smaller of the two values is: 6
### Solution
```cpp=
#include <iostream>
#include <iomanip>
using namespace std;
double Average(int num_A, int num_B);
int main()
{
int num1, num2, num3;
cout << "Please enter three integers:\n";
cin >> num1 >> num2 >> num3;
if (num1 > num2 && num1 > num3) // 判斷 num1 是不是最大的
cout << Average(num2, num3);
else if (num2 > num1 && num2 > num3) // 判斷 num2 是不是最大的
cout << Average(num1, num3);
else // 否則最大的就是 num3
cout << Average(num1, num2);
return 0;
}
double Average(int num_A, int num_B)
{
cout << "The smaller of the two values is: ";
return (num_A + num_B) / 2.0; // 記得加 2.0這樣才會用 double 除
}
```
## 3rd homework
### Description
請編寫一個完整的程序,使用 void 函數 read_input 讀取正整數並將其儲存在形參 max 中。 然後,程式定義了一個void函數compute,它有一個int類型的形參,用於將1到max區間內能被3或5整除的數字相加。 main函數依序呼叫read_input和compute。
### Example
參考執行畫面如下:(粗體字為使用者輸入的)
Please enter a positive integer: **10**
The sum of numbers divisible by three and five is: 33
### Solution
```cpp=
#include <iostream>
#include <iomanip>
using namespace std;
void read_input(int &max);
void compute(int max);
int main()
{
int max;
read_input(max);
compute(max);
return 0;
}
void read_input(int &max)
{
cout << "Please enter a positive integer: ";
cin >> max;
}
void compute(int max)
{
int sum = 0;
for (int i = 1; i <= max; i++) // 從 1 加到max
{
if (i % 3 == 0 || i % 5 == 0) // 餘數等於 0 才將值加進sum
sum += i;
}
cout << "The sum of numbers divisible by three and five is: " << sum;
}
```
## 4th homework
### Description
請寫一個完整的程式來讀取檔案「infile.txt」中的所有實數。 (假設我們不知道檔案中有多少個數字。)然後,程式得出這些數字的平均值並將其輸出到檔案「outfile.txt」。 (顯示小數點後兩位) 請檢查檔案開啟是否成功。
### Example
**infile.txt**
```
1
2
3
4
5
6
7
8
9
10
```
**outfile.txt**
```
5.50
```
### Solution
```cpp=
#include <iostream>
#include <iomanip>
#include <fstream>
using namespace std;
int main()
{
ifstream infile;
ofstream outfile;
infile.open("infile.txt");
if (infile.fail()) // 如果沒有成功開啟檔案
{
cout << "Input file opening failed.\n";
exit(1);
}
outfile.open("outfile.txt");
if (outfile.fail()) // 如果沒有成功開啟檔案
{
cout << "Output file opening failed.\n";
exit(1);
}
double sum = 0, count = 0, next;
// sum總和 count控制迴圈次數 next文件讀取進來的暫存變數
while (infile >> next) // 條件式用文件輸入 直到文件沒有數值為止
{
sum += next; // 將文件讀取進來的值加到sum裡
count++;
}
outfile << fixed << setprecision(2) << sum / count; // 輸出sum到該檔案
infile.close();
outfile.close();
cout << "Success!";
return 0;
}
```
# 初階期中考題
## 1st exam(20分)
### Description
請撰寫一支程式讓使用者輸入n個賓客的名字與身份(兩者皆為字串),一開始先讓使用者輸入n的值,再一一讓使用者輸入每個名字與身份,若某個使用者身份為"VIP",則輸出"VIP confirmed"於螢幕上,最後輸出一共有多少個具有VIP身份的賓客。
### Example
參考執行畫面如下:(粗體字為使用者輸入的)
Please input the number of guests:
**3**
Please input the name and status of guest#1:
**Alex VIP**
VIP confirmed!
Please input the name and status of guest#2:
**Bob normal**
Please input the name and status of guest#3:
**Charlie VIP**
VIP confirmed!
There are 2 VIP.
### Solution
```cpp=
#include <iostream>
#include <string>
using namespace std;
int main()
{
int user_num, vip_num = 0; // 儲存使用者數量 VIP數量初始為 0
string user_name, user_status; // 儲存使用者名稱 用戶身份
cout << "Please input the number of guests:\n";
cin >> user_num;
for (int i = 1; user_num >= i; i++) // 使用者從 1 開始加
{
cout << "Please input the name and status of guest#" << i << ':' << endl;
cin >> user_name >> user_status;
if (user_status == "VIP") // 如果用戶為 VIP 進去做
{
cout << "VIP confirmed!\n";
vip_num += 1; // 把 VIP 加 1
}
}
cout << "There are " << vip_num << " VIP.";
return 0;
}
```
## 2nd exam(25分)
### Description
數學中某個大於1的實數之floor值指的是所有小於或等於該實數的正整數中最大的一個正整數,請撰寫求取floor值的程式,其先讓使用者輸入一個實數(假設使用者輸入的值皆為大於1的實數),接著請使用for loop求出該實數的floor值。
### Example
參考執行畫面如下:(粗體字為使用者輸入的)
Please input a real value: **4.89**
The answer is 4
### Solution
```cpp=
#include <iostream>
using namespace std;
int main()
{
double number;
int value;
cout << "Please input a real value: ";
cin >> number;
for (value = 1; value <= (number - 1); value++) // 加 value 的值
; // 不做任何事
cout << "The answer is " << value << endl;
return 0;
}
```
## 3rd exam(25分)
### Description
在C++中欲產生隨機值需加入下方程式碼:
```
#include <ctime>
using namespace std;
int main()
{
srand(time(NULL));
int Answer = rand() % 10;
}
```
此時Answer將儲存一個介於0至9之間的值。請撰寫一猜數字的遊戲,程式一開始先自行隨機產生一個介於0至9之間的值為答案,接著讓使用者連續猜數字,若使用者輸入的值大於答案則輸出"Too high!",若小於答案則輸出"Too low!",若等於答案則輸出"Bingo!",使用者需作答到猜對為止。
### Example
參考執行畫面如下:(粗體字為使用者輸入的)
Your guess?
**4**
Too high!
Guess again!
**1**
Too low!
Guess again!
**3**
Too high!
Guess again!
**2**
Bingo!
### Solution
```cpp=
#include <iostream>
#include <ctime>
using namespace std;
int main()
{
int num, Answer;
srand(time(NULL)); // 取得時間序列
Answer = rand() % 10; // 取亂數 0-9
cout << "Your guess?\n";
while (true) // 無限迴圈
{
cin >> num;
if (num == Answer)
break; // 直到使用者猜到答案 跳出 while
else
cout << ((num > Answer) ? "Too high!\n" : "Too low!\n");
// 如果使用者輸入大於 Answer 輸出 Too high! 否則輸出 Too low!
cout << "Guess again!\n";
}
cout << "Bingo!";
return 0;
}
```
## 4th exam(30分)
### Description
東華漢堡想要製作一個點餐系統,提供以下四種套餐:火烤鴨腿堡套餐160元、蜜汁雞腿堡套餐150元、叉燒豬肉堡套餐130元、香煎植物肉堡套餐140元。請撰寫一點餐程式,可讓使用者點餐(上述四種套餐編號依序為1、2、3、4,點餐即輸入編號,可重覆選取某一套餐,若非輸出以上數字即輸出"Wrong input!"),每輸入一編號後,系統會詢問是否需要再點餐,回答'Y'或是'y'即讓使用者再點餐,輸入其他值即結束點餐,點餐結束後會輸出餐點總金額於螢幕上。請使用switch
### Example
參考執行畫面如下:(粗體字為使用者輸入的)
Please enter your choice:
**3**
叉燒豬肉堡套餐!
Do you want another meal?
**Y**
Please enter your choice:
**2**
蜜汁雞腿堡套餐!
Do you want another meal?
**y**
Please enter your choice:
**1**
火烤鴨腿堡套餐!
Do you want another meal?
**y**
Please enter your choice:
**3**
叉燒豬肉堡套餐!
Do you want another meal?
**Y**
Please enter your choice:
**5**
Wrong input!
Do you want another meal?
**Y**
Please enter your choice:
**4**
香煎植物肉堡套餐!
Do you want another meal?
**n**
The total price is $710
### Solution
```cpp=
#include <iostream>
using namespace std;
int main()
{
int total = 0;
char code, QA;
do
{
cout << "Please enter your choice:\n";
cin >> code;
switch (code)
{
case '1':
cout << "火烤鴨腿堡套餐!\n";
total += 160;
break;
case '2':
cout << "蜜汁雞腿堡套餐!\n";
total += 150;
break;
case '3':
cout << "叉燒豬肉堡套餐!\n";
total += 130;
break;
case '4':
cout << "香煎植物肉堡套餐!\n";
total += 140;
break;
default:
cout << "Wrong input!\n";
break;
}
cout << "Do you want another meal?\n";
cin >> QA;
} while ((QA == 'y') || (QA == 'Y'));
cout << "The total price is $" << total;
return 0;
}
```
# 初階期末考題
## 1st exam(15分)
### Description
請撰寫一支完整程式,程式中有三個function,第一個function名為Input,有三個call-by-reference參數,function中會讓使用者輸入三個參數的值;第二個function名為Compute,有三個參數,當中會求出三個參數的平均值與標準差,並將平均值減去標準差後回傳;第三個function名稱ShowResult,其有一個double參數,會將該參數的值輸出到螢幕上。在main function中連續呼叫Input、Compute與ShowResult,以讓使用者輸入三個實數,並計算後輸出值。
$$
s = \sqrt{\frac{1}{n-1} \sum_{i=1}^{n} (x_i - \overline{x})^2}
$$
### Example
參考執行畫面如下:(粗體字為使用者輸入的)
Please input three numbers:
**3**
**4**
**5**
The answer is 3
### solution
```cpp=
#include <iostream>
#include <cmath>
using namespace std;
void Input(double &a, double &b, double &c);
double Compute(double a, double b, double c);
void ShowResult(double ans);
int main()
{
double a, b, c;
Input(a, b, c);
ShowResult(Compute(a, b, c));
}
void Input(double &a, double &b, double &c)
{
cout << "Please input three numbers:\n";
cin >> a >> b >> c;
}
double Compute(double a, double b, double c)
{
double sun = 0, ave = 0;
ave = (a + b + c) / 3.0;
sun = sqrt(((a - ave) * (a - ave) + (b - ave) * (b - ave) + (c - ave) * (c - ave)) / 2.0);
return ave - sun;
}
void ShowResult(double ans)
{
cout << "The answer is " << ans;
}
```
## 2nd exam(25分)
### Description
請撰寫一完整程式,在程式中開啟兩個檔案infile1.txt及infile2.txt,兩個檔案存有相同個數的數字(帶小數的數字),但一開始並不知道檔案中有幾個數字,程式接下來會一一將兩個檔案中的數字讀出來,每從兩個檔案中各讀一個數字出來時,會將兩個數字相乘並加總起來,最後再將加總的數字除以infile1.txt中的數字個數,並將得到的值輸出於檔案outfile.txt中。(開啟檔案請檢查是否開啟成功)
### Example
**infile1.txt**
```
1.0
2.0
3.0
4.0
```
**infile2.txt**
```
5.0
6.0
7.0
8.0
```
**outfile.txt**
```
17.5
```
### solution
```cpp=
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ifstream infile1, infile2;
ofstream outfile;
infile1.open("infile1.txt");
if (infile1.fail()) // 如果沒有成功開啟檔案
{
cout << "Input file1 opening failed.\n";
exit(1);
}
infile2.open("infile2.txt");
if (infile2.fail()) // 如果沒有成功開啟檔案
{
cout << "Input file2 opening failed.\n";
exit(1);
}
outfile.open("outfile.txt");
if (outfile.fail()) // 如果沒有成功開啟檔案
{
cout << "Output file opening failed.\n";
exit(1);
}
double sum = 0, count = 0, next1 = 0, next2 = 0;
while ((infile1 >> next1) && (infile2 >> next2))
{
sum += next1 * next2;
count++;
}
outfile << sum / count;
infile1.close();
infile2.close();
outfile.close();
cout << "Success!";
return 0;
}
```
## 3rd exam(25分)
### Description
請撰寫一完整程式包含兩個function,第一個為 void input(double Score[], int Size),其中 Size變數的值即為Score的長度,在這function中,會讓使用者從鍵盤輸入Score的每個element的值;另一function為void convert(double Score[], int Size),在convert中,會把Score 的每個element 值開根號再乘以10。在main function中,先宣告一個double的array變數Score,其長度為一const的global變數NumOfScores,NumOfScores的初始值為10,接著連續呼叫input及convert兩個function,最後把Score的每個element的值輸出到螢幕上。(程式輸入、輸出資料前,請先輸出提示字串)
### Example
參考執行畫面如下:(粗體字為使用者輸入的)
Please input 10 values:
**2**
**4**
**9**
**16**
**25**
**25**
**16**
**9**
**4**
**2**
result:
14.1421
20
30
40
50
50
40
30
20
14.1421
### solution
```cpp=
#include <iostream>
#include <cmath>
using namespace std;
void input(double Score[], int Size);
void convert(double Score[], int Size);
int const NumOfScores = 10; // 全域變數 array 的長度
int main()
{
double Score[NumOfScores];
input(Score, NumOfScores);
convert(Score, NumOfScores);
cout << "result:\n";
for (int i = 0; i < NumOfScores; i++)
{
cout << Score[i] << endl;
}
return 0;
}
void input(double Score[], int Size)
{
cout << "Please input 10 values:\n";
for (int i = 0; i < NumOfScores; i++)
{
cin >> Score[i];
}
}
void convert(double Score[], int Size)
{
for (int i = 0; i < NumOfScores; i++)
{
Score[i] = sqrt(Score[i]) * 10;
}
}
```
## 4th exam(35分)
### Description
假設一架小客機有兩排座椅,每排各5個座位,請寫一支程式供乘客預約座位,程式主畫面為一選單提示使用者以下操作,每一操作完成後皆會再顯示主畫面選單以讓使用者進行下一個操作:
1. 輸入V或v以顯示已完成預約的座位編號及預約者名字。
2. 輸入R或r預約座位。當輸入R之後,隨即讓使用者輸入座位編號(哪一排哪一列,需檢查使用者是否輸入合理的座位編號,若非正確編號,則請使用者再選擇另一個座位編號,編號皆從0開始),若該座位目前無人預約,則再讓使用者填入名字(設為一字串)後將該名字填入該座位,完成預約。若該座位已有人預約,則請使用者再選擇另一個座位編號,直到完成預約為止。
3. 輸入C或c以取消預約。當輸入C之後,隨時讓使用者輸入座位編號(哪一排哪一列,需檢查使用者是否輸入合理的座位編號,若非正確編號,則請使用者再選擇另一個座位編號,編號皆從0開始),若該座位目前無人預約,則輸出一錯誤訊息回到主畫面。若該座位有人預約,則取消其預約(刪去該座位的預約人名)。
4. 若輸入的值非V, v, R, r, C, c其中之一,則輸出一錯誤訊息。
5. 若所有座位皆已被預約,則結束程式。
請以一個二維陣列來記錄座位預約狀態
### Example
參考執行畫面如下:(粗體字為使用者輸入的)
V is for showing reservations, R is for reserving, and C is for cancellation.
What is your choice?
**R**
Please tell us which seat you want to reserve.
**1 3**
Please enter your name:
**Alex**
Thank you!
V is for showing reservations, R is for reserving, and C is for cancellation.
What is your choice?
**V**
1, 3, Alex
V is for showing reservations, R is for reserving, and C is for cancellation.
What is your choice?
**r**
Please tell us which seat you want to reserve.
**1 3**
This seat has been taken. Please choose again.
Please tell us which seat you want to reserve.
**0 1**
Please enter your name:
**Bob**
Thank you!
V is for showing reservations, R is for reserving, and C is for cancellation.
What is your choice?
**V**
0, 1, Bob
1, 3, Alex
V is for showing reservations, R is for reserving, and C is for cancellation.
What is your choice?
**R**
Please tell us which seat you want to reserve.
**1 1**
Please enter your name:
**Charlie**
Thank you!
V is for showing reservations, R is for reserving, and C is for cancellation.
What is your choice?
**C**
Please tell us which seat you want to cancel.
**1 1**
Thank you!
V is for showing reservations, R is for reserving, and C is for cancellation.
What is your choice?
**V**
0, 1, Bob
1, 3, Alex
V is for showing reservations, R is for reserving, and C is for cancellation.
What is your choice?
### solution
```cpp=
#include <iostream>
#include <string>
using namespace std;
const int COLS = 2;
const int ROWS = 5;
void V(const string Score[][ROWS]);
void R(string Score[][ROWS]);
void C(string Score[][ROWS]);
int main()
{
string Score[COLS][ROWS];
char choice;
do
{
cout << "V is for showing reservations, R is for reserving, and C is for cancellation.\n";
cout << "What is your choice?\n";
cin >> choice;
switch (choice)
{
case 'V':
case 'v':
V(Score);
break;
case 'R':
case 'r':
R(Score);
break;
case 'C':
case 'c':
C(Score);
break;
default:
cout << "Error input. Please choose again." << endl;
break;
}
} while (choice == 'V' || choice == 'v' || choice == 'R' || choice == 'r' || choice == 'C' || choice == 'c');
cout << "Program ends." << endl;
return 0;
}
void V(const string Score[][ROWS])
{
for (int i = 0; i < COLS; i++)
{
for (int j = 0; j < ROWS; j++)
{
if (!Score[i][j].empty()) // Score 如果裡面有值
cout << i << ", " << j << ", " << Score[i][j] << endl;
}
}
}
void R(string Score[][ROWS])
{
int col, row;
cout << "Please tell us which seat you want to reserve." << endl;
cin >> col >> row;
if (col < 0 || col >= COLS || row < 0 || row >= ROWS)
{
cout << "Invalid seat number. Please choose again." << endl;
return;
}
if (!Score[col][row].empty()) // Score 如果裡面有值
{
cout << "This seat has been taken. Please choose again." << endl;
}
else
{
cout << "Please enter your name:" << endl;
string name;
cin >> name;
Score[col][row] = name;
cout << "Thank you!" << endl;
}
}
void C(string Score[][ROWS])
{
int col, row;
cout << "Please tell us which seat you want to cancel." << endl;
cin >> col >> row;
if (col < 0 || col >= COLS || row < 0 || row >= ROWS)
{
cout << "Invalid seat number. Please choose again." << endl;
return;
}
if (Score[col][row].empty()) // Score 如果裡面沒有值
{
cout << "No reservation found for this seat. Please choose again." << endl;
}
else
{
Score[col][row] = ""; // 清空
cout << "Reservation canceled. Thank you!" << endl;
}
}
```
# 關於作者
國立東華大學 資訊管理學系 一年級學生
信箱:411235041@gms.ndhu.edu.tw
IG:sumo20020711