---
# System prepended metadata

title: 初階程式設計113年考古
tags: [東華資管]

---

---
title: 東華資管
tags: 東華資管考古題
---
# 東華大學資管系初階程設113年考古
>老師：劉英和教授
>原文書:Problem Solving with C++ 10th(不重要，反正也用不到)
> [112考古](https://hackmd.io/@sumo0711/SyFipiOfA)
:::danger
僅供參考，發現我寫錯的話就代表你很聰明，看得懂錯在哪
::: 


# 初階實習題

## 財務指標
>評估一間公司的存貨流動性可以參考「存貨周轉率」與「存貨周轉天數」這兩個財務指標。請撰寫一支完整的程式，程式當中先後讓使用者輸入一家公司的營業成本、期初存貨與期末存貨（假設皆為帶小數點的數字，單位為萬元），之後再輸出該公司的存貨周轉率與存貨周轉天數 。（讓使用者輸入數值之前請先印出提示字串）
存貨周轉率 = 營業成本 ÷ 平均存貨
平均存貨 = (期初存貨+期末存貨) ÷ 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

### ans
```cpp=
#include <iostream>
using namespace std;

int main()
{
    double cos, bi, ei;
    double it, dsi;

    cout << "Please input the cost of sales, beginning inventory, ending inventory.\n";
    cin >> cos >> bi >> ei;

    double avi = (bi + ei) / 2;
    it = cos / avi;
    dsi = 365 / it;

    cout << "The inventory turnover is " << it << endl;
    cout << "The days sales in inventory is " << dsi << endl;

    return 0;
}

```
## 吉尼係數
吉尼係數（Gini index）為衡量年所得分配公平程度的一個指標。以下圖為例，實際所得分配曲線（紅線）和所得分配絕對平等線（綠線）之間的面積為A，實際所得分配曲線（紅線）和所得分配絕對不平等線（藍線）之間的面積為B，吉尼係數的算法為 A/(A+B)
請撰寫一程式讓使用者輸入A與B的值
接著計算吉尼係數後輸出於螢幕上。
（A與B皆為實數，讓使用者輸入數值之前請先印出提示字串）
![image](https://hackmd.io/_uploads/rJEWV0L9ll.png)
### Example

	參考執行畫面如下：（粗體字為使用者輸入的）
    Please input the areas A and B:
    21.4
    50.5
    The Gini Index is 0.297636
    
### ans
```cpp=   
#include <iostream>
using namespace std;

int main()
{
	double area_A, area_B;

	cout << "Please input the areas A and B:\n";
	cin >> area_A >> area_B;

	double GiniIndex = area_A / (area_A + area_B);

	cout << "The Gini Index is " << GiniIndex << endl;

	return 0;
}
```
## BMI計算

請撰寫一支完整的程式，程式當中先後讓使用者輸入身高、體重（假設皆為帶小數點的數字）
之後再輸出其使用者的BMI值。
（讓使用者輸入數值之前請先印出提示字串，請輸出至小數點後兩位。）
BMI = weight / (height * height)
假設使用者輸入的身高單位為公尺，體重單位為公斤。
不用對輸出格式做限制。
### Example
    參考執行畫面如下：（粗體字為使用者輸入的）
    How tall are you?
    1.81
    How much do you weigh?
    80.0
    Your BMI is 24.42
### ans
```cpp=   
#include <iostream>
#include <iomanip>  // 為了設定小數點輸出精度
using namespace std;

int main()
{
    double height, weight, bmi;

    cout << "How tall are you?" << endl;
    cin >> height;

    cout << "How much do you weigh?" << endl;
    cin >> weight;

    bmi = weight / (height * height);

    cout << fixed << setprecision(2);
    cout << "Your BMI is " << bmi << endl;

    return 0;
}
```
### 承上題
承上題，在輸出使用者的BMI值之後
若使用者的BMI小於18，就輸出 “You are slim.”
若是大於或等於18，就輸出 “You are fit.”。

    參考執行畫面如下：（粗體字為使用者輸入的）
    How tall are you?
    1.81
    How much do you weigh?
    80.0
    Your BMI is 24.42
    You are fit.
### ans
```cpp=   
#include <iostream>
#include <iomanip>  // 為了設定小數點輸出精度
using namespace std;

int main()
{
    double height, weight, bmi;

    cout << "How tall are you?" << endl;
    cin >> height;

    cout << "How much do you weigh?" << endl;
    cin >> weight;

    bmi = weight / (height * height);

    cout << fixed << setprecision(2);
    cout << "Your BMI is " << bmi << endl;

    if (bmi < 18)
    {
        cout << "You are slim." << endl;
    }
    else
    {
        cout << "You are fit." << endl;
    }

    return 0;
}

```
## 復利計算
請撰寫一支完整的程式以計算數年後的本利和，該程式一開始先讓使用者輸入目前本金多少
再讓使用者輸入欲知多少年後的本利和，接著輸出算得的本利和（輸出至小數點後兩位）
假設本金及本利和皆可為帶小數的數字，年利率為2%，採複利計算。
### Example
    Please input account balance and years to maturity:
    100
    5
    Your final balance will be 110.41
### ans
```cpp=   
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;

int main() {
    double principal;  // 本金，可以帶小數
    int years;         // 幾年後
    
    cout << "Please input account balance and years to maturity:" << endl;
    cin >> principal >> years;
    
    double rate = 0.02;  // 年利率 2%
    double finalBalance = principal * pow(1 + rate, years);
    
    cout << fixed << setprecision(2);
    cout << "Your final balance will be " << finalBalance << endl;
    
    return 0;
}
```
## TTDI
世界經濟論壇（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 TDDI of each country.
    Japan 5.3
    USA 5.1   
    Taiwan 5.5
    The country with the highest TDDI is Taiwan and its TDDI is 5.5
### Ans
```cpp=
#include <iostream>
#include <string>
using namespace std;

int main() {
    int n;
    cout << "Please input how many countries do you have." << endl;
    cin >> n;

    cout << "Please input the name and TDDI of each country." << endl;

    string country, maxCountry;
    double tddi, maxTddi = -1.0;  // TTDI 為大於0實數，初始化設 -1 保證第一筆會更新

    for (int i = 0; i < n; i++) {
        cin >> country >> tddi;
        if (tddi > maxTddi) {
            maxTddi = tddi;
            maxCountry = country;
        }
    }

    cout << "The country with the highest TDDI is "
         << maxCountry << " and its TDDI is " << maxTddi << endl;

    return 0;
}
```
## 快樂餐廳
請為快樂餐廳撰寫一支點餐程式，程式中會讓使用者輸入欲選擇的套餐代號（代號為一個字母）
輸入後，若代號為A(或a)，則輸出 good choice，若為B (或b) ，則輸出 wonderful choice
若為C (或c) ，則輸出 excellent choice，若為其他字母，則輸出 wrong input!。
（請使用if, else if，讓使用者輸入數值之前，記得先輸出提示語）
### Example
    Please input your choice: a
    good choice
### ans
```cpp=
#include <iostream>
using namespace std;

int main() {
    char code;
    cout << "Please input your choice: ";
    cin >> code;

    if (code == 'A' || code == 'a') {
        cout << "good choice" << endl;
    } 
    else if (code == 'B' || code == 'b') {
        cout << "wonderful choice" << endl;
    } 
    else if (code == 'C' || code == 'c') {
        cout << "excellent choice" << endl;
    } 
    else {
        cout << "wrong input!" << endl;
    }

    return 0;
}
```
### 承上題
承上題，請使用switch，讓使用者輸入數值之前，記得先輸出提示語
### ans
```cpp=
#include <iostream>
using namespace std;

int main() {
    char code;
    cout << "Please input your choice: ";
    cin >> code;

    switch (code) {
        case 'A':
        case 'a':
            cout << "good choice" << endl;
            break;
        case 'B':
        case 'b':
            cout << "wonderful choice" << endl;
            break;
        case 'C':
        case 'c':
            cout << "excellent choice" << endl;
            break;
        default:
            cout << "wrong input!" << endl;
            break;
    }

    return 0;
}
```
## Double (作業給的就全英文，那我也沒辦法)
Write a C++ program that reads two whole numbers into two variables of type double and then outputs the whole number part of the quotient and the remainder when the first number is divided by the second.
### ans
```cpp=
#include <iostream>
using namespace std;

int main() {
    double x, y;  

    cout << "Enter two whole numbers: ";
    cin >> x >> y;

    int a = static_cast<int>(x); // 轉成整數
    int b = static_cast<int>(y); // 轉成整數

    int q = a / b;  // 商
    int r = a % b;  // 餘數

    cout << "Q: " << q << endl;
    cout << "R: " << r << endl;

    return 0;
}
```
## do while
 Write a C++ program that repeatedly asks a user to input exam scores (in whole numbers)
    After the user inputs a score, the user determines if the insertion continues by inputting a letter. When ‘y’ or ‘Y’ is input, the insertion continues. Otherwise, the input terminates. Next, this program outputs the sum of these scores. Be sure to prompt for input and label all output.
### ans
```cpp=
#include <iostream>
using namespace std;

int main() {
    int score;     // 單次輸入的成績
    int sum = 0;   // 總分
    char cont;     // 是否繼續輸入

    do {
        cout << "exam score :";
        cin >> score;
        sum += score;  // 加到總分

        cout << " enter another score? (y/Y to continue): ";
        cin >> cont;

    } while (cont == 'y' || cont == 'Y');

    cout << "sum=: " << sum << endl;

    return 0;
}
```
## 
Please write a complete program that reads a positive whole number and stores it in variablemax. 
If max is divisible by 2 or 3, increase max by 1 until it is not. For the numbers in the interval 1 to max that are divisible by 2 or 5, compute their average and then output the result
### ans
```cpp=
#include <iostream>
using namespace std;

int main() {
    long long max;                 // 讀入的正整數
    if (!(cin >> max) || max <= 0) return 0;

    // 若 max 可被 2 或 3 整除，就一直 +1 直到不可被 2 或 3 整除
    while (max % 2 == 0 || max % 3 == 0) {
        ++max;
    }

    // 計算 1..max 之間可被 2 或 5 整除的數的平均值
    long long sum = 0;
    long long cnt = 0;
    for (long long i = 1; i <= max; ++i) {
        if (i % 2 == 0 || i % 5 == 0) {
            sum += i;
            ++cnt;
        }
    }

    if (cnt == 0) {
        cout << 0 << '\n';         // 沒有符合的數，避免除以 0
    } else {
        cout.setf(ios::fixed);
        cout.precision(6);
        cout << (static_cast<double>(sum) / cnt) << '\n';
    }
    return 0;
}
```
## 費波那契數列
假定一對兔子在它們出生整整兩個月以後可以生一對小兔子，其後每隔一個月又可以再生一對小兔子。假定現在在一個籠子裡有一對剛生下來的小兔子，請問需要多長的時間才會超過1000對兔子？

假設

小兔出生後兩個月就能長成大兔，可以生小兔。

可生育的大兔子都不會累，每個月可以生一對小兔，而且剛好是雄雌各一。

兔子永生不死。

Fn 表示第 n 代兔子的數目。
而F1 = F2 = 1
而當 n≧3 時，Fn = F(n-1) + F(n–2)
所以F1=1 F2=1 F3=2 F4=3 F5=5 F6=8 以此類推

請輸出每個月的兔子對數變化和需要幾個月才會超過1000對兔子
範例輸出:
![image](https://hackmd.io/_uploads/S1Yx_LD5eg.png)
### ans
```cpp=
#include <iostream>
using namespace std;

int main() {
    long long p = 1, c = 1, n;
    int m = 2, t = 1000;

    cout << "F1:1 F2:1 ";
    while (c <= t) {
        n = p + c;
        p = c;
        c = n;
        m++;
        cout << "F" << m << ":" << c << " ";
    }

    cout << "要超過1000隻兔子需要" << m << "個月\n";
    return 0;
}
```
## For Loop/do while loop
請撰寫一支完整的程式，該程式可讓 3 個使用者各自輸入若干個正整數，每個使用者在輸入若干個正整數後，再輸入一個小於或等於 0 的數字代表輸入結束，每個使用者輸入結束後
會輸出該使用者所輸入的數字（不包含最後那個小於或等於 0 的數字）的總合。
（第一層 loop 請使用 for loop，第二層 loop 請使用 do while loop，可參考第三章投影片第 99 頁的程式）。

### ans
```cpp=
#include <iostream>
using namespace std;

int main()
{
	for (int Ucnt = 0; Ucnt < 3; Ucnt++)
	{
		int Value, Sum = 0;

		cout << "Please input values:\n";

		do
		{
			cin >> Value;

			if (Value > 0)
				Sum += Value;

		} while (Value > 0);
		
		cout << "The sum is " << Sum << endl << endl;
	}

	return 0;
}
```
## 平方根
請撰寫一支完整的程式，該程式一開始請使用者輸入兩個double數字
接著會輸出第一個數字的平方根與第二個數字的絕對值的和（讓使用者輸入數值之前，記得先輸出提示語）
### Example
    Please input two numbers:
    9
    -5
    The answer is 8

### ans
```cpp=
#include <iostream>
#include <cmath>  

using namespace std;

int main() {
    double num1, num2;

    cout << "Please input two numbers:" << endl;
    cin >> num1 >> num2;

    double result = sqrt(num1) + fabs(num2);

    cout << "The answer is " << result << endl;

    return 0;
}
```
## Function add
請撰寫一支完整程式，程式中有一個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
### ans
```cpp=
#include <iostream>
using namespace std;

int AddFive(int Value) {
    return Value + 5;
}

int main() {
    int Num;

    cout << "Please input a value:" << endl;
    cin >> Num;

    int result = AddFive(Num);

    cout << "The answer is " << result << endl;

    return 0;
}
```

## Ceil and Floor Sum
請撰寫一支完整的程式，該程式一開始請使用者輸入兩個double數字，然後將兩個數字當做參數傳給Compute這個function
而在Compute中計算第一個數字的ceiling與第二個數字的floor的和後，將此算得的和當做回傳值
最後在main function中輸出該算得的和。（讓使用者輸入數值之前，記得先輸出提示語）
### Example
    Please input two numbers:
    9.3
    7.2
    The answer is 17
### ans
```cpp=
#include <iostream>
#include <cmath>   r
using namespace std;

int Compute(double a, double b) {
    return static_cast<int>(ceil(a) + floor(b));
}

int main() {
    double num1, num2;

    cout << "Please input two numbers:" << endl;
    cin >> num1 >> num2;

    int result = Compute(num1, num2);

    cout << "The answer is " << result << endl;

    return 0;
}
```
## Compute Average
請撰寫一支完整的程式，當中包含兩個名稱為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
### ans
```cpp=
#include <iostream>
using namespace std;

double ave(double a, double b) {
    return (a + b) / 2.0;
}

double ave(double a, double b, double c) {
    return (a + b + c) / 3.0;
}

int main() {
    int n;
    cout << "How many values you have?" << endl;
    cin >> n;

    if (n == 2) {
        double x, y;
        cout << "Please enter two values" << endl;
        cin >> x >> y;
        cout << "The average is " << ave(x, y) << endl;
    } 
    else if (n == 3) {
        double x, y, z;
        cout << "Please enter three values" << endl;
        cin >> x >> y >> z;
        cout << "The average is " << ave(x, y, z) << endl;
    } 
    else {
        cout << "wrong input" << endl;
    }

    return 0;
}
```

## b^2-4ac
請撰寫一支程式計算 b2 – 4 × a × c 的值，該程式的演算法有下列三個步驟：
讓使用者輸入變數 a, b, c 的值（皆為整數）
計算 b2 – 4 × a × c 的值
輸出第二步驟所算得的值於螢幕上，請分別將三個步驟各自寫成一個function，然後在 main function 中呼叫這三個function 以完成該程式。a
### Example
    Please input three values:
    5
    20
    3
    The result is 340
### ans
```cpp=
#include <iostream>
using namespace std;

void InputValues(int &a, int &b, int &c) {
    cout << "Please input three values:" << endl;
    cin >> a >> b >> c;
}

int ComputeResult(int a, int b, int c) {
    return b * b - 4 * a * c;
}

void OutputResult(int result) {
    cout << "The result is " << result << endl;
}

int main() {
    int a, b, c;
    InputValues(a, b, c);          
    int result = ComputeResult(a, b, c);  
    OutputResult(result);         
    return 0;
}
```
## 本利和
請撰寫一支完整的程式以計算數年後的本利和，該程式有一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
### ans
```cpp=
#include <iostream>
#include <iomanip>  
using namespace std;

//  call-by-reference
void Input(float &bal, int &yrs) {
    cout << "Please input account balance and years to maturity:" << endl;
    cin >> bal >> yrs;
}

//  call-by-value
float Compute(float bal, int yrs) {
    const float rate = 0.02f;  // 年利率 2%
    for (int i = 0; i < yrs; i++) {
        bal = bal * (1 + rate);
    }
    return bal;
}

int main() {
    float bal;
    int yrs;

    Input(bal, yrs);                 
    float finalBal = Compute(bal, yrs);  
    cout << fixed << setprecision(2);
    cout << "Your final balance will be " << finalBal << endl;

    return 0;
}
```
## Sum of Two Numbers
請撰寫一完整的程式，其中定義一function名稱為SUM，其formal parameter為兩個double 變數FirstPar跟SecondPar，其回傳值為一double值，在SUM中，會計算FirstPar與SecondPar的和並回傳。另有一function稱為Input，其有兩個double的call-by-reference參數，在Input中會讓使用者輸入兩個數字儲存在兩個參數中。在main function中，會宣告兩double變數First及Second，並呼叫Input讓使用者輸入這兩變數的值，隨後呼叫SUM function，把First、Second當成參數傳給SUM，並把SUM的回傳值輸出至螢幕上。 （輸出、輸入數值之前請先印出提示字串）
### Example
    Please input two values:
    3
    5
    The sum is 8
### ans
```cpp=
#include <iostream>
using namespace std;

double SUM(double FirstPar, double SecondPar) {
    return FirstPar + SecondPar;
}

void Input(double &FirstPar, double &SecondPar) {
    cout << "Please input two numbers:" << endl;
    cin >> FirstPar >> SecondPar;
}

int main() {
    double First, Second;

    Input(First, Second);

    double result = SUM(First, Second);
    cout << "The sum is " << result << endl;

    return 0;
}
```
## 開讀檔
請撰寫一完整程式，將檔案”infile.txt”中的數字(可能含有自然數，即有小數點的數字)全部讀入（infile.txt中有3個數字），然後求出這些數字各自的平方根後，再求這些平方根之平均數，再把下列文字輸出到檔案”outfile.txt”中：
	
	mean: (求得的平均數)

需檢查檔案開啟是否成功

### ans
```cpp=
#include <iostream>
#include <fstream>
#include <cmath>
#include <iomanip>
using namespace std;

int main() {
    ifstream infile("infile.txt");
    if (!infile) {
        cout << "err_infile" << endl;
        return 1;
    }

    double a, b, c;
    infile >> a >> b >> c;
    infile.close();

    double mean = (sqrt(a) + sqrt(b) + sqrt(c)) / 3.0;

    ofstream outfile("outfile.txt");
    if (!outfile) {
        cout << "err_outfile" << endl;
        return 1;
    }

    outfile << fixed << setprecision(6);
    outfile << "mean: " << mean << endl;
    outfile.close();

    return 0;
}
```
## 計算三數中最小兩數的平均 (題目原文我也沒辦法)
Write a function Average that takes two formal parameters of int and returns a value of double that is the average of the two formal parameters (the average could be a decimal). In the main function, the user has to input three values of type int. Then, the smaller two values are taken as arguments to call the function Average. Then, the return value is output to the screen.
### ans
```cpp=
#include <iostream>
#include <algorithm>  
using namespace std;

double Average(int x, int y) {
    return (x + y) / 2.0;  
}

int main() {
    int a, b, c;
    cout << "Please input three integer values:" << endl;
    cin >> a >> b >> c;

    int arr[3] = {a, b, c};
    sort(arr, arr + 3); 

    double result = Average(arr[0], arr[1]);

    cout << "The average of the two smaller values is " << result << endl;

    return 0;
}
```

## 依餘數規則計算數列冪次和
Please write a complete program where the users first input a positive whole number x by calling a function Input. Then, the result of the following expression is computed using a function called Compute. The result is shown on the screen by the function Show.

![image](https://hackmd.io/_uploads/HkeAbDP5lg.png)

### ans
```cpp=
#include <iostream>
#include <cmath>
using namespace std;

int Input() {
    int x;
    cout << "Please input a positive integer: ";
    cin >> x;
    return x;
}

long long Compute(int x) {
    long long sum = 0;
    for (int k = 1; k <= x; k++) {
        int r = k % 3;
        int p;
        if (r == 1) p = 1;
        else if (r == 2) p = 2;
        else p = 3;
        sum += (long long)pow(k, p);
    }
    return sum;
}

void Show(long long res) {
    cout << "The result is " << res << endl;
}

int main() {
    int x = Input();             
    long long res = Compute(x);  
    Show(res);                   
    return 0;
}
```
## 開讀檔-2
請撰寫一完整程式，程式中開啟檔案input1.txt及output1.txt，（要檢查檔案是否開啟成功），接著一一讀入input1.txt中的每個整數（input1.txt如附檔），但假設我們並不知道input1.txt中有幾個數字，接著計算出第奇數個數字（即第1、3、5、…個數字）的總和與第偶數個數字（即第2、4、6、…個數字）的總和，再將這兩個總和相減後的值輸出到檔案output1.txt中（只要輸出該值即可）。譬如附檔input1.txt中的第奇數個數字的總和為176（=11+33+55+77），第偶數個數字的總和為220，相減後的值為-44，則output1.txt中就記錄-44。
### ans
```cpp=
#include <iostream>
#include <fstream>
#include <cstdlib>
using namespace std;

int main()
{
	ifstream fin;
	ofstream fout;

	fin.open("input1.txt");
	if(fin.fail())
	{
		cout << "fail to open input.txt";
		exit(1);
	}

	fout.open("output1.txt");
	if(fout.fail())
	{
		cout << "fail to open output.txt";
		exit(1);
	}

	int counter = 0;
	int token;
	int sum_odd = 0, sum_even = 0;

	while(fin >> token)
	{
		counter++;

		if(counter % 2 == 1)  
			sum_odd += token; //odd
		else
			sum_even += token; //even
	}

	fout << (sum_odd - sum_even);

	fin.close();
	fout.close();

	return 0;
}
```

## 開讀檔-3
請撰寫一完整程式，程式中開啟檔案input2.txt及output2.txt，（要檢查檔案是否開啟成功），接著一一讀入input2.txt中的內容並輸出至output2.txt，但若intpu2.txt的內容中有大寫的英文字，輸出至output2.txt時就要轉換成小寫，若內容中有小寫的英文字，輸出時就要轉換成大寫。（提示：用isupper、islower檢查讀入的符號是否是大寫或是小寫英文字母。）
### ans
```cpp=
#include <fstream>
#include <iostream>
#include <cctype>
using namespace std;

int main()
{
	ifstream fin;
	ofstream fout;

	fin.open("input2.txt");
	if (fin.fail())
	{
		cout << "open input-file error";
		exit(1);
	}

	fout.open("output2.txt");
	if (fin.fail())
	{
		cout << "open output-file error";
		exit(1);
	}

	char next;
	fin.get(next);

	while (!fin.eof())
	{
		if (isupper(next))
			fout << static_cast<char>(tolower(next));
		else if (islower(next))
			fout << static_cast<char>(toupper(next));
		else
			fout << next;

		fin.get(next);
	}

	fin.close();
	fout.close();

	return 0;
}
```

## 火星耶耶
    但其實這幾題都是開讀檔案，沒差多少
###
地球與火星各有其體積與質量，請撰寫一支程式由planets.txt中讀入這兩顆行星各自的體積與質量（步驟一），然後計算每個行星的密度（質量除以體積）（步驟二），最後輸出每顆行星的密度於檔案densities.txt（步驟三）。請各以一個function實作這三個步驟，main function中連續呼叫這三個function。main function中先宣告ifstream與ofstream的變數，將兩變數連結到planets.txt與densities.txt後，再呼叫第一個步驟的function以讀取行星資料。planets.txt中一列有一個行星的名稱與兩個數字，兩個數字分別為該顆行星的體積與質量。densities.txt中每一列寫上一顆行星的名稱及其密度，密度輸出至小數點後兩位。

### ans
```cpp=
#include <fstream>
#include <iostream>
#include <cstdlib>
#include <string>
using namespace std;

void read_data(ifstream& fin, float& EarthVolume, float& EarthMass, 
	float& MarsVolume, float& MarsMass);

void compute_densities(float EarthVolume, float EarthMass, float& EarthDensity, 
	float MarsVolume, float MarsMass, float& MarsDensity);

void show_results(ofstream& fout, float EarthDensity, float MarsDensity);

int main()
{
	ifstream fin;
	ofstream fout;

	fin.open("planets.txt");
	if (fin.fail())
	{
		cout << "Fail to open planets.txt.";
		exit(1);
	}

	fout.open("densities.txt");
	if (fout.fail())
	{
		cout << "Fail to open densities.txt.";
		exit(1);
	}

	float EarthVolume, EarthMass, EarthDensity, MarsVolume, MarsMass, MarsDensity;

	read_data(fin, EarthVolume, EarthMass, MarsVolume, MarsMass);
	compute_densities(EarthVolume, EarthMass, EarthDensity, MarsVolume, MarsMass, MarsDensity);
	show_results(fout, EarthDensity, MarsDensity);

	fin.close();
	fout.close();

	return 0;
}

void read_data(ifstream& fin, float& EarthVolume, float& EarthMass,
	float& MarsVolume, float& MarsMass)
{
	string Token;
	fin >> Token >> EarthVolume >> EarthMass;
	fin >> Token >> MarsVolume >> MarsMass;
}

void compute_densities(float EarthVolume, float EarthMass, float& EarthDensity,
	float MarsVolume, float MarsMass, float& MarsDensity)
{
	EarthDensity = EarthMass / EarthVolume;
	MarsDensity = MarsMass / MarsVolume;
}

void show_results(ofstream& fout, float EarthDensity, float MarsDensity)
{
	fout.setf(ios::fixed);
	fout.setf(ios::showpoint);
	fout.precision(2);

	fout << "Earth " << EarthDensity << endl;
	fout << "Mars " << MarsDensity << endl;
}
```
# 期中考

## 第一題
1.	請撰寫一支程式讓使用者依序輸入一個學生的名字、年級以及學號。接著再依序輸出其學號、年級及名字。（15分）參考執行結果如下： 
###
    Please input the name, grade, and ID of a student:
    David 
    3 
    411435000
    The ID, grade, and name of the student are 
    411435000
    3
    David
### ans
```cpp=
#include <iostream>
#include <string>
using namespace std;

int main() {
    string name;
    int grade;
    string id;

    cout << "Please input the name, grade, and ID of a student:" << endl;
    cin >> name >> grade >> id;

    cout << "The ID, grade, and name of the student are " << endl;
    cout << id << endl;
    cout << grade << endl;
    cout << name << endl;

    return 0;
}
```
## 第二題
請撰寫一支程式讓使用者輸入n位學生各自兩個科目的成績（均為整數），學生人數n由使用者決定。
每輸入一位學生的兩個成績後，只要最少有一個成績高於或等於90，就輸出 “Excellent!”，不然就輸出 “Wonderful!”。請使用for loop。（20分）參考執行結果如下：
###
    How many students? 3
    Please input the scores of student #1
    95 97
    Excellent!
    Please input the scores of student #2
    93 82
    Excellent!
    Please input the scores of student #3
    80 89
    Wonderful!
### ans
```cpp=
#include <iostream>
using namespace std;

int main() {
    int n;
    cout << "How many students? ";
    cin >> n;

    for (int i = 1; i <= n; i++) {
        int score1, score2;
        cout << "Please input the scores of student #" << i << endl;
        cin >> score1 >> score2;

        if (score1 >= 90 || score2 >= 90) {
            cout << "Excellent!" << endl;
        } else {
            cout << "Wonderful!" << endl;
        }
    }

    return 0;
}
```
## 第三題
3.	請撰寫一支程式讓使用者輸入若干位學生各自兩個科目的成績（均為整數），若某次輸入兩個成績皆為-1代表輸入結束，並輸出 “That’s all!”。每輸入一位學生的兩個成績後，若兩個成績均高於或等於90分，則輸出 “Excellent!”；若一個成績高於或等於90分，另一個低於90分，則輸出 “Wonderful!”；若兩個成績皆高於或等於80分但都低於90分，則輸出 “Marvelous!”；若一個成績高於或等於80分但低於90分，另一個低於80分，則輸出 “Fantastic!”；若兩個成績皆高於或等於70分但都低於80分，則輸出 “Incredible!”；最後，若分數不為上述狀況之一，則輸出 “Remarkable!”。請使用while loop以及if - else if。（25分）參考執行結果如下：
###
    Please input the scores of a student
    95 95
    Excellent!
    Please input the scores of a student
    95 87
    Wonderful!
    Please input the scores of a student
    86 84
    Marvelous!
    Please input the scores of a student
    89 79
    Fantastic!
    Please input the scores of a student
    71 76
    Incredible!
    Please input the scores of a student
    74 65
    Remarkable!
    Please input the scores of a student
    64 32
    Remarkable!
    Please input the scores of a student
    -1 -1
    That’s all!
### ans
```cpp=
#include <iostream>
using namespace std;

int main() {
    int score1, score2;

    while (true) {
        cout << "Please input the scores of a student" << endl;
        cin >> score1 >> score2;

        if (score1 == -1 && score2 == -1) {
            cout << "That’s all!" << endl;
            break;
        }

        if (score1 >= 90 && score2 >= 90) {
            cout << "Excellent!" << endl;
        } 
        else if ((score1 >= 90 && score2 < 90) || (score2 >= 90 && score1 < 90)) {
            cout << "Wonderful!" << endl;
        } 
        else if (score1 >= 80 && score1 < 90 && score2 >= 80 && score2 < 90) {
            cout << "Marvelous!" << endl;
        } 
        else if ((score1 >= 80 && score1 < 90 && score2 < 80) || (score2 >= 80 && score2 < 90 && score1 < 80)) {
            cout << "Fantastic!" << endl;
        } 
        else if (score1 >= 70 && score1 < 80 && score2 >= 70 && score2 < 80) {
            cout << "Incredible!" << endl;
        } 
        else {
            cout << "Remarkable!" << endl;
        }
    }

    return 0;
}
```
## 第四題
4.	請為管理學院撰寫一支程式以供輸入與計算各系GPA平均值。使用者需要一一輸入每位管院同學的GPA（一個實數，同學數目未知）。當輸入一位同學的GPA之前，需要先輸入該同學的系別，各系有其代碼：資管系（I或i）、國企系（B或b）、企管系（M或m）、會計系（A或a）、財金系（F或f）、觀遊系（T或t）。輸入完代碼後再輸入GPA。當使用者輸入代碼E或e時，代表輸入結束。程式將輸出各系所的平均GPA，輸出至小數點後兩位。若是輸入上述以外的代碼，會輸出 “Wrong input!”。當某系沒有任何一位學生的成績時，會輸出 “There is no student in Information Management.”（以資管系舉例）（40分）請使用switch，參考執行結果如下：

###

    Please input the department of the student:
    I
    Please input GPA:
    4.11
    Please input the department of the student:
    i
    Please input GPA:
    3.56
    Please input the department of the student:
    M
    Please input GPA:
    4.15
    Please input the department of the student:
    m
    Please input GPA:
    3.48
    Please input the department of the student:
    A
    Please input GPA:
    4.01
    Please input the department of the student:
    a
    Please input GPA:
    3.92
    Please input the department of the student:
    F
    Please input GPA:
    4.05
    Please input the department of the student:
    f
    Please input GPA:
    3.46
    Please input the department of the student:
    T
    Please input GPA:
    4.01
    Please input the department of the student:
    t
    Please input GPA:
    3.27
    Please input the department of the student:
    K
    Wrong input!
    Please input the department of the student:
    E
    The average GPA of each department is as follows.
    Information Management: 3.84
    There is no student in International Business.
    Business Administration: 3.82
    Accounting: 3.97
    Finance: 3.76
    Tourism, Recreation and Leisure Studies: 3.64
### ans
```cpp=
#include <iostream>
#include <iomanip>
using namespace std;

int main() {
    // 紀錄各系 GPA 總和與人數
    double sumI = 0, sumB = 0, sumM = 0, sumA = 0, sumF = 0, sumT = 0;
    int cntI = 0, cntB = 0, cntM = 0, cntA = 0, cntF = 0, cntT = 0;

    char dept;
    while (true) {
        cout << "Please input the department of the student:" << endl;
        cin >> dept;

        if (dept == 'E' || dept == 'e') {
            break;
        }

        double gpa;
        switch (dept) {
            case 'I':
            case 'i':
                cout << "Please input GPA:" << endl;
                cin >> gpa;
                sumI += gpa;
                cntI++;
                break;
            case 'B':
            case 'b':
                cout << "Please input GPA:" << endl;
                cin >> gpa;
                sumB += gpa;
                cntB++;
                break;
            case 'M':
            case 'm':
                cout << "Please input GPA:" << endl;
                cin >> gpa;
                sumM += gpa;
                cntM++;
                break;
            case 'A':
            case 'a':
                cout << "Please input GPA:" << endl;
                cin >> gpa;
                sumA += gpa;
                cntA++;
                break;
            case 'F':
            case 'f':
                cout << "Please input GPA:" << endl;
                cin >> gpa;
                sumF += gpa;
                cntF++;
                break;
            case 'T':
            case 't':
                cout << "Please input GPA:" << endl;
                cin >> gpa;
                sumT += gpa;
                cntT++;
                break;
            default:
                cout << "Wrong input!" << endl;
        }
    }

    cout << "The average GPA of each department is as follows." << endl;
    cout << fixed << setprecision(2);

    if (cntI > 0) cout << "Information Management: " << sumI / cntI << endl;
    else cout << "There is no student in Information Management." << endl;

    if (cntB > 0) cout << "International Business: " << sumB / cntB << endl;
    else cout << "There is no student in International Business." << endl;

    if (cntM > 0) cout << "Business Administration: " << sumM / cntM << endl;
    else cout << "There is no student in Business Administration." << endl;

    if (cntA > 0) cout << "Accounting: " << sumA / cntA << endl;
    else cout << "There is no student in Accounting." << endl;

    if (cntF > 0) cout << "Finance: " << sumF / cntF << endl;
    else cout << "There is no student in Finance." << endl;

    if (cntT > 0) cout << "Tourism, Recreation and Leisure Studies: " << sumT / cntT << endl;
    else cout << "There is no student in Tourism, Recreation and Leisure Studies." << endl;

    return 0;
}
```
# 期末考
## 第一題
請撰寫一完整程式，在程式中開啟兩個檔案infile1.txt及infile2.txt，兩個檔案存有相同個數的數字（帶小數的數字），但一開始並不知道檔案中有幾個數字，程式接下來會一一將兩個檔案中的數字讀出來，每從兩個檔案中各讀一個數字出來時，會將兩個數字相乘並加總起來，最後再將加總的數字除以infile1.txt中的數字個數，並將得到的值輸出於檔案outfile.txt中；例如infile1.txt中有1、2、3、4這四個數字而infile2.txt中有5、6、7、8這四個數字，則outfile.txt中的值會是70（1 * 5 + 2 * 6 + 3 * 7 + 4 * 8 = 70）。（開啟檔案請檢查是否開啟成功）（20分）
### ans
```cpp=
#include <iostream>
#include <fstream>
#include <iomanip>
using namespace std;

int main() {
    ifstream infile1("infile1.txt");
    ifstream infile2("infile2.txt");
    ofstream outfile("outfile.txt");

    if (!infile1 || !infile2 || !outfile) {
        cerr << "Error: cannot open one of the files." << endl;
        return 1;
    }

    double num1, num2;
    double sum = 0.0;
    int count = 0;

    while (infile1 >> num1 && infile2 >> num2) {
        sum += num1 * num2;
        count++;
    }

    if (count > 0) {
        double result = sum / count;
        outfile << fixed << setprecision(6) << result << endl;
    } else {
        outfile << "No data." << endl;
    }

    infile1.close();
    infile2.close();
    outfile.close();

    return 0;
}
```
## 第二題
請撰寫一支完整程式，程式中有三個function，第一個function名為Input，有三個參數，function中會讓使用者輸入三個參數的值；第二個function名為Compute，有三個參數，當中會求出三個參數的平均值與標準差，並將平均值減去標準差後回傳；第三個function名為ShowResult，其有一個參數，會將該參數的值輸出到螢幕上。在main function中連續呼叫Input、Compute與ShowResult，以讓使用者輸入三個實數，並計算後輸出值。（開啟檔案請檢查是否開啟成功）（25分）
![image](https://hackmd.io/_uploads/B1uTUwv9ex.png)
### ans
```cpp=
#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;

void Input(double &a, double &b, double &c) {
    cout << "Please input three real numbers:" << endl;
    cin >> a >> b >> c;
}

double Compute(double a, double b, double c) {
    double mean = (a + b + c) / 3.0;
    double variance = ((a - mean) * (a - mean) +
                       (b - mean) * (b - mean) +
                       (c - mean) * (c - mean)) / (3.0 - 1.0); 
    double std = sqrt(variance);
    return mean - std;
}

void ShowResult(double result) {
    cout << fixed << setprecision(6);
    cout << "The result is " << result << endl;
}

int main() {
    double x, y, z;

    Input(x, y, z);               
    double result = Compute(x, y, z); 
    ShowResult(result);           

    return 0;
}
```

## 第三題
請撰寫一支完整程式，當中開啟infile.txt，接著將檔案中的內容完整複製到outfile.txt，但是其中大寫英文字母要變成小寫，小寫英文字母要變成大寫，若有空格，要換成-，若為數字0、1、2，要換成zero、one、two。需檢查開啟檔案是否失敗，若失敗就結束程式。請在main function宣告讀取檔案的兩個變數並分別連結到兩個檔案，讀取與複製檔案內容由一個function（名為Conversion）完成。(25分)
附圖為範例
![image](https://hackmd.io/_uploads/BkTwwvD5ee.png)
### ans
```cpp=
#include <iostream>
#include <fstream>
#include <cctype>
using namespace std;

void Conversion(ifstream &infile, ofstream &outfile) {
    char ch;
    while (infile.get(ch)) {
        if (isupper(ch)) {
            outfile << static_cast<char>(tolower(ch));
        } 
        else if (islower(ch)) {
            outfile << static_cast<char>(toupper(ch));
        } 
        else if (ch == ' ') {
            outfile << "-";
        } 
        else if (ch == '0') {
            outfile << "zero";
        } 
        else if (ch == '1') {
            outfile << "one";
        } 
        else if (ch == '2') {
            outfile << "two";
        } 
        else {
            outfile << ch;
        }
    }
}

int main() {
    ifstream infile("infile.txt");
    ofstream outfile("outfile.txt");

    if (!infile || !outfile) {
        cerr << "Error: cannot open infile.txt or outfile.txt" << endl;
        return 1;
    }

    Conversion(infile, outfile);

    infile.close();
    outfile.close();

    return 0;
}

```
## 第四題

有一遊戲當中Mario與Princess Peach合作要將一個大水桶倒滿水。假設大水桶的容量大於0公升而小於或等於100公升，而Mario每次能倒入n公升的水、Princess Peach每次能倒入m公升的水，n與m都是整數，玩家可決定每次由Mario或是Princess Peach倒水，每次倒水後，螢幕會顯示尚須多少公升的水才可將大水桶裝滿。若玩家倒入的水剛好可裝滿大水桶，則為挑戰成功，若倒入的水超過大水桶容量，則為挑戰失敗，各會在螢幕上顯示You success!與You fail!的訊息。遊戲會持續進行直至挑戰成功或是失敗。請撰寫該遊戲的程式，程式一開始隨機決定大水桶的容量，再讓玩家決定n與m的值。然後就不斷讓玩家選擇由Mario倒水（輸入o或是O）或是Princess Peach（輸入p或是P）倒水，直至挑戰成功或是失敗為止。選擇由Mario倒水會呼叫一function，當中會計算倒入n公升之後，大水桶還有多少容量可裝水，然後顯示With pleasure!後將剩餘容量顯示於螢幕上。若選擇由Princess Peach倒水會呼叫另一function，當中會計算倒入m公升之後，大水桶還有多少容量可裝水，然後顯示Oh no!後將剩餘容量顯示於螢幕上。若輸入其他字母則會顯示Wrong input!後，再讓使用者再選擇一次。為預防使用者輸入不只一個字母，故要在輸入後清空input stream。(30分)

產生大於0而小於或等於100之隨機值的作法如下：

```cpp=
#include <ctime>
using namespace std;

int main()
{
srand(time(NULL));
int Value = rand() % 100 + 1;
}
```
### 
    例子一：
    The bucket's volume is 12 liters.
    Please determine the values of n and m:
    2
    3
    Mario or Princess Peach?
    o
    With pleasure!
    The remaining volume is 10.

    Mario or Princess Peach?
    oo
    With pleasure!
    The remaining volume is 8.

    Mario or Princess Peach?
    k
    Wrong selection!

    Mario or Princess Peach?
    p
    Oh no!
    The remaining volume is 5.

    Mario or Princess Peach?
    p
    Oh no!
    The remaining volume is 2.

    Mario or Princess Peach?
    p
    Oh no!
    The remaining volume is -1.

    You fail!
    例子二:
    The bucket's volume is 12 liters.
    Please determine the values of n and m:
    2
    3
    Mario or Princess Peach?
    o
    With pleasure!
    The remaining volume is 10.

    Mario or Princess Peach?
    oo
    With pleasure!
    The remaining volume is 8.

    Mario or Princess Peach?
    k
    Wrong selection!

    Mario or Princess Peach?
    p
    Oh no!
    The remaining volume is 5.

    Mario or Princess Peach?
    p
    Oh no!
    The remaining volume is 2.

    Mario or Princess Peach?
    o
    With pleasure!
    The remaining volume is 0.

    You success!
### ans
```cpp=
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;

int pourByMario(int remaining, int n) {
    int after = remaining - n;
    cout << "With pleasure!\n";
    cout << "The remaining volume is " << after << ".\n\n";
    return after;
}

int pourByPeach(int remaining, int m) {
    int after = remaining - m;
    cout << "Oh no!\n";
    cout << "The remaining volume is " << after << ".\n\n";
    return after;
}

int main() {
    srand(static_cast<unsigned int>(time(NULL)));
    int capacity = rand() % 100 + 1;

    cout << "The bucket's volume is " << capacity << " liters.\n";
    cout << "Please determine the values of n and m:\n";

    int n, m;
    if (!(cin >> n)) return 0;
    if (!(cin >> m)) return 0;

    int remaining = capacity;

    while (cin.get() != '\n');

    while (true) {
        cout << "Mario or Princess Peach?\n";

        char choice;
        if (!(cin.get(choice))) break; 

        while (cin.get() != '\n');

        if (choice == 'o' || choice == 'O') {
            remaining = pourByMario(remaining, n);
        } else if (choice == 'p' || choice == 'P') {
            remaining = pourByPeach(remaining, m);
        } else if (choice == '\n' || choice == '\r') {
            cout << "Wrong selection!\n\n";
            continue;
        } else {
            cout << "Wrong selection!\n\n";
            continue;
        }

        if (remaining == 0) {
            cout << "You success!\n";
            break;
        } else if (remaining < 0) {
            cout << "You fail!\n";
            break;
        }
    }

    return 0;
}

```
# 一些不重要的事情ლ(╹◡╹ლ)
嗨，各位大一的同學早安、午安、晚安
這份是因為之前有好心人寫過112年度的考古，所以我才打算整理的
如果對於這份中的程式或其他程式有任何問題可以私訊我，(另外我在找有打資安或有興趣的朋友)
特別感謝我的朋友洪于媗、吳偲瑜以及陳佳妤三位大好人幫我檢查
另外，希望到時候有能力的人，能夠幫助你們的下一屆
信箱:411335035@gms.ndhu.edu.tw
Instagram: [shihyukai1211_z](https://www.instagram.com/shihyukai1211_z/)
