---
# System prepended metadata

title: 程式設計(C/C++)TA
tags: [diaries]

---

---
tags: diaries
---
# 程式設計(C/C++)TA

> C++學習資源 https://www.csie.ntu.edu.tw/~b98902112/cpp_and_algo/index.html

## 上學期作業

### 第1週
無。

### 第2週
:::spoiler {state="close"} P2-14 Q4
- C語言版本
```c=
#include <stdio.h>
#include <stdlib.h>

int main(void) {
	printf("我也會寫 C 程式\n");
	system("pause");
}
```
:::

:::spoiler {state="close"} P2-14 Q3
- C語言版本
```c=
#include <stdio.h>
#include <stdlib.h>

int main(void) {
	printf("我\n也\n會\n寫\nC\n程\n式\n");
	system("pause"); 
}
```
:::

### 第3週

:::spoiler {state="close"} 整數與浮點數比較
- C語言版本
```c=
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[]) {
	int integer = 10;
	float fp = 10.0;
	
	printf("整數的是: %d\n", (integer/3)*3);
	//	10/3 = 3
	//	3 * 3 = 9
	printf("浮點數的是: %f\n", (fp/3)*3);
	//	10/3 = 3.3333 
	//	3.3333 * 3 = 10 
	return 0;
}
```
:::

:::spoiler {state="close"} P3-40 Q2
- C語言版本
```c=
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[]) {
	int x = 3, y = 3, z = 3;
	z += ++x * y++;
	//	z = 3 + (1+3) * 3;
	printf("result: %d", z);
	return 0;
}
```
:::

:::spoiler {state="close"} P3-40 Q3
- C語言版本
```c=
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[]) {
	int x;
	float y, result;
	
	x = 15;
	y = 7.125;
	result = (float)x/y;
	
	printf("%f", result);
	return 0;
}
```
:::

:::spoiler {state="close"} P3-41 Q4
- C語言版本
```c=
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[]) {
	int a = 2, b = 6, c = 4, d = 5, e = 6;
	float answer;
	
	answer = ((b*b) - 4 * a * c) / (d + (1 / (2.0*e)));
	// (2.0*e)的 2.0 不可以為 2 必須為浮數點 
	
	printf("%f \n", answer);
	return 0;
}
```
:::

### 第4週

:::spoiler {state="close"} P3-41 Q7
- C語言版本
```c=
#include <stdio.h>
#include <stdlib.h>

void main(int argc, char *argv[]) {
	short int a = 30000, b = 30000;
	short unsigned int c;
	// short 的範圍為-32768~32767
	
	c = a + b;
	printf("%d", c);
	
	return 0;
}
```
:::

:::spoiler {state="close"} P3-42 Q9
- C語言版本
```c=
#include <stdio.h>
#include <stdlib.h>

void main(int argc, char *argv[]) {
	int a = 4, b = 5;
	
	printf("%f \n", (float)a/b);
	
	return 0;
}
```
:::

:::spoiler {state="close"} P3-31 Q1
- C語言版本
```c=
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[]) {
	printf("今日降價\"25%%\"，請把握機會。");
	
	return 0;
}
```
:::

:::spoiler {state="close"} P4-31 Q3
- C語言版本
```c=
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[]) {
	float a = 12.38;
	
	printf("%+010.4f", a);
	// 預設小數後會補6位 整數需要4位 => 6+4=10 
}
```
:::
### 第5週

:::spoiler {state="close"} P4-32 Q4
- C語言版本
```c=
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[]) {
	char name[10];
	int score[3] = {0};
	
	printf("請輸入姓名:");
	scanf("%s", &name);
	printf("請輸入計概成績:");
	scanf("%d", &score[0]);
	printf("請輸入數學成績:");
	scanf("%d", &score[1]);
	printf("請輸入英文成績:");
	scanf("%d", &score[2]);
	
	printf("統計中............. \n");
	printf("%s的成績如下:\n", name);
	printf("===================\n");
	
	printf("    計概 : %d\n", score[0]);
	printf("    數學 : %d\n", score[1]);
	printf("    英文 : %d\n", score[2]);
	
	printf("------------------\n");
	int total = score[0] + score[1] + score[2];
	float average = (float)total / 3;
	
	printf("    總分 : %d \n", total);
	printf("    平均 : %.2f \n", average);
	return 0;
}
```
:::

:::spoiler {state="close"} P4-32 Q6
- C語言版本
```c=
#include <stdio.h>
#include <math.h>

int main(int argc, char *argv[]) {
	float value, p = 3.0;
	
	printf("請輸入數值:");
	scanf("%f", &value);
	
	printf("%.3f 的 %.0f 次方為 %.3f", value, p, pow(value, p));
	return 0;
}
```
:::

:::spoiler {state="close"} P4-32 Q8
- C語言版本
```c=
#include <stdio.h>
#include <math.h>

#define meter 3.306 
#define yard 3.95

int main(int argc, char *argv[]) {
	float value;
	
	printf("請輸入坪數:");
	scanf("%f", &value);
	
	printf("%.0f坪 = %.2f平方公尺\n", value, value*meter);
	printf("%.0f坪 = %.2f平方碼\n", value, value*yard);
	
	return 0;
}
```
:::

:::spoiler {state="close"} P4-33 Q10
- C語言版本
```c=
#include <stdio.h>
#include <stdlib.h>

void main(void)
{
	int input;
	scanf("%d", &input);
	
	if(input%2 == 0){
		printf("偶數");
	}else{
		printf("奇數");
	}
}
```
:::

### 第6週
:::spoiler {state="close"} 判斷奇數偶數
- C語言版本
```c=
#include <stdio.h>
#include <stdlib.h>

void main(void)
{
	int input;
	scanf("%d", &input);
	
	if(input%2 == 0){
		printf("偶數");
	}else{
		printf("奇數");
	}
}
```
:::

:::spoiler {state="close"} 求絕對值
- C語言版本
```c=
#include <stdio.h>
#include <stdlib.h>

void main(void)
{
	int input, count;
	scanf("%d", &input);
	 
	if(input < 0){
		input = 0 - input;
	}
	
//	input = abs(input);
    printf("%d\n", input);
}
```
:::


:::spoiler {state="close"} 判斷 正、負、零(用單一選擇)
- C語言版本
```c=
#include <stdio.h>
#include <stdlib.h>

void main(void)
{
	int input;
	scanf("%d", &input);
	
	if(input > 0){		
		printf("正數");
	}else if(input < 0){		
		printf("負數");
	}else(
		printf("零");
	}
}
```
:::

:::spoiler {state="close"} 判斷 正、負、零(用巢狀選擇)
- C語言版本
```c=
#include <stdio.h>
#include <stdlib.h>

void main(void)
{
	int input;
	scanf("%d", &input);
	
	if(input > 0){		
		printf("正數");
	}else if(input < 0){		
		printf("負數");
	}else{
		printf("零");
	}
}
```
:::

### 第7週
:::spoiler {state="close"} P5-58 Q6 計程車費率
- C語言版本
```c=
#include <stdio.h>
#include <stdlib.h>
#include <math.h>

void main(void){
	float distance;
	int km_distance, cost, type;
	
	printf("搭乘時間 日間:1 夜間:2 請選擇>>");
	scanf("%d", &type);
	printf("請輸入里程(公里)[小數點可精確至公尺]:");
	scanf("%f", &distance);
	
	km_distance = distance * 1000;
	if(type == 1){
		if(km_distance <= 1500){
			cost = 70;
		}else{
			km_distance -= 1500;
			cost = 70 + maxInt(km_distance, 300) * 5;
			// cost = 70 + ceil(km_distance/300) * 5;
			// 為啥ceil 不能用...? 
		}
	}else{
		if(km_distance <= 1250){
			cost = 70;
		}else{
			km_distance -= 1250;
			cost = 70 + maxInt(km_distance, 250) * 5;
		}
	}
	printf("%d", cost);
}

int maxInt(int meter, int div){
	int response = meter / div;
	if(meter%div != 0) response += 1;
	return response;
}
```
:::


:::spoiler {state="close"} P5-58 Q7 輸入西元年，判斷閏年(用複合條件)
- C語言版本

![](https://i.imgur.com/bnYy9wd.png)

```c=
#include <stdio.h>
#include <stdlib.h>

void main(void)
{
	int x;
	printf("多少年?");
	scanf("%d",&x);
	
	if(x % 4 ==0 && x % 100 !=0 || x % 400==0){
		 printf("是閏年");		
	}else{
		 printf("不是閏年");
	}
 } 
``` 
:::

:::spoiler {state="close"} P5-58 Q7 判斷閏年(用巢狀選擇)
- C語言版本
```c=
#include <stdio.h>
#include <stdlib.h>

int main(void){
	int y, leap;
	printf("輸入西元年:");
	scanf("%d", &y);
	
	// leap 0為平年  leap 1為閏年 ~~(波動拳)~~
	if(y % 4 == 0){
		if(y % 100 == 0){
			if(y % 400 == 0){
                leap = 1;
			}else{
				leap = 0;
			}
		}else{
			leap = 1;
		}
    }else{
		leap = 0;
	}
	
	if(y % 1000 == 0){
		leap = 1;
	}
	
	leap ? printf("是閏年") : printf("不是閏年");
}
```
:::

 ### 第8週
 
:::spoiler {state="close"} 輸入血壓值，判斷血壓分類。
> 題目說明: 如圖
> ![](https://i.imgur.com/bnsjiQx.png)
- C++語言版本
```cpp=
#include <iostream>
using namespace std;

int main(void)
{
	int diastolic, systolic, level = 0;
	cout << "input diastolic blood pressure: ";
	cin >> diastolic;
	cout << "input systolic blood pressure: ";
	cin >> systolic;
	
	if(diastolic < 120 && systolic < 80) level = 1;
	if(diastolic >= 120 && diastolic < 130 && systolic < 80) level = 2;
	if( (diastolic >= 130 && diastolic < 140) || (systolic >= 80 && systolic < 90) ) level = 3;
	if( (diastolic >= 140 && diastolic < 180) || (systolic >= 90 && systolic < 120) ) level = 4;
	if(diastolic >= 180 || systolic >= 120) level = 5;
	
	switch (level){
		case 1: cout << "正常血壓" << endl; break;
		case 2: cout << "血壓升高" << endl; break;
		case 3: cout << "高血壓一級" << endl; break;
		case 4: cout << "高血壓二級" << endl; break;
		case 5: cout << "高血壓危象" << endl; break;
	} 
}
```
:::

:::spoiler {state="close"} P5-59 Q8 英文大小寫
> 題目說明
> 請撰寫一個程式，接受使用者輸入一個字元，如果字元微小寫英文字母就將之轉換為大寫英文字母後輸出；如果字元為大寫字母，就將之轉換為小寫英文字母後輸出；如果輸入的並非英文字母，則輸出"您所輸入的並不是英文字母"。
> 
- C++語言版本
```cpp=
#include <iostream>
using namespace std;

int main(void)
{
	char c;
	int res;
	cin >> c;
	
	if( (int)c >= 65 && (int)c <= 90){
		res = (int)c + 32;
		cout << (char)res << endl;
	}else if( (int)c >= 97 && (int)c <= 122){
		res = (int)c - 32;
		cout << (char)res << endl;
	}else{
		cout << "您所輸入的並不是英文字母" << endl; 
	}
}
```
:::

:::spoiler {state="close"} 計算 BMI，並分級
- C++語言版本
> 題目說明: 如圖
> ![](https://i.imgur.com/cXUM6QP.png)
```cpp=
#include <iostream>
#include <string>
using namespace std;

int main(void)
{
	int height, weight;
	float bmi;
	string result;
	
	cout << "請輸入身高cm: ";
	cin >> height;
	cout << "請輸入體重kg: ";
	cin >> weight;
	
	bmi = weight / (height * height * 0.0001);
	if(bmi < 18.5) result = "體重過輕";
	if(bmi >= 18.5 && bmi < 24) result = "正常範圍";
	if(bmi >= 24 && bmi < 27) result = "過重";
	if(bmi >= 27 && bmi < 30) result = "輕度肥胖";
	if(bmi >= 30 && bmi < 35) result = "中度肥胖";
	if(bmi >= 35) result = "重度肥胖";
	
	cout << result << endl;
}
```
:::

___

### 第9週(期中考週)
:::danger
**期中考猜題**
1. 英文大小寫(ASCII碼的轉換)
2. 第八週的題目-血壓值
:::

___

### 第10週
:::spoiler {state="close"} 級數一 `s=1^2+2^2+3^2+...+n^2`
- C++語言版本
```cpp=
#include <iostream> 
using namespace std;

int main(void)
{
	int n;
	while(cin >> n){
		int sum = 0;
		for(int i = 1; i <= n; i++){
			sum += i*i;
		}
		cout << sum << endl;
	}
}
```
:::

:::spoiler {state="close"} 級數二 `s=1*2+2*3+3*4+....+n*(n+1)`
- C++語言版本 
```cpp=
#include <iostream> 
using namespace std;

int main(void)
{
	int n;
	while(cin >> n){
		int sum = 0;
		for(int i = 1; i <= n; i++){
			sum += i*(i+1);
		}
		cout << sum << endl;
	}
}
```
:::

### 第11週

:::spoiler {state="close"} 級數三 s=1+2+3+4+5-6-7....(+-)n
- C++語言版本
```cpp=
#include <iostream> 
using namespace std;

int main(void)
{
	int n;
	while(cin >> n){
		int sum = 0;
		for(int i = 1; i <= n; i++){
			if((i%7 == 6) || (i%7 == 0)){
				sum -= i;
			}else{
				sum += i;
			}
		}
		cout << sum << endl;
	}
}
```
:::

:::spoiler {state="close"} 輸入正整數n，列出其所有因數
- C++語言版本
```cpp=
#include <iostream> 
#include <math.h>
using namespace std;

int main(void)
{
	int n;
	while(cin >> n){
		for(int i = 1; i<=n; i++){
			if(n % i == 0) cout << i << " " ;
		}
		cout << endl;
	}
}
```
:::

:::spoiler {state="close"} 輸入正整數n，計算n的因數個數 k。 根據k，判斷n是否為質數。
- C++語言版本
```cpp=
#include <iostream> 
#include <math.h>
using namespace std;

int main(void)
{
	int n;
	while(cin >> n){
		int k = 0;
		for(int i = 2; i<n; i++){
			if(n % i == 0){
                k += 1;
            }    
		}
		
		(k == 0)?cout << "是" << endl : cout << "否" << endl;
	}
}
```

google unit test framework範例
``` cpp=
#include <gtest/gtest.h>
 
namespace
{
    bool IsPrime(int n)
    {
        if (n < 2) {
            return false;
        }
 
        if (n % 2 == 0) {
            return n == 2;
        }
 
        for (int i = 3; ; i += 2)
        {
            if (i > n / i) {
                break;
            }
 
            if (n % i == 0) {
                return false;
            }
        }
 
        return true;
    }
}
 
TEST(TestIsPrime_3, TestAll)
{
    EXPECT_FALSE(IsPrime(1));
    EXPECT_FALSE(IsPrime(0));
    EXPECT_FALSE(IsPrime(-2));
    EXPECT_FALSE(IsPrime(6));
    EXPECT_FALSE(IsPrime(40));
    EXPECT_FALSE(IsPrime(25));
 
    EXPECT_TRUE(IsPrime(2));
    EXPECT_TRUE(IsPrime(3));
    EXPECT_TRUE(IsPrime(5));
    EXPECT_TRUE(IsPrime(19));
    EXPECT_TRUE(IsPrime(89));
}
```
:::

### 第12週

:::spoiler {state="close"} P5-58 Q2
> 題目說明: 使用迴圈設計一個程式，找出2~100中所有的質數，每5個質數後換行顯示，執行結果如下。
> 2       3       5       7       11
> 13      17      19      23      29
> 31      37      41      43      47
> 53      59      61      67      71
> 73      79      83      89      97
> (需設置寬度配置 %-md m為數字)

- C語言版本
```c=
#include <stdio.h>
#include <math.h>

int main(int argc, char *argv[]) {
	int i, j, row = 0;
	for(i = 2; i < 100; i++){
		int prime = 0;
		for(j = 2; j < (i-1); j++ )
			prime = ((i%j) == 0)?1:prime;
		
		if(!prime){
			printf("%-8d", i);
			row++;
			if((row%5) == 0) printf("\n");
		}
	}
}
```
:::
:::spoiler {state="close"} P5-58 Q3
> 題目說明: 使用for迴圈設計一個`(0~9 * 0*9)`的偶數乘法表。執行結果如下(請特別注意乘數與被乘數的排列方式)
> 
| `0*0=0` | `2*0=0`  | `4*0=0` | `6*0=0` | `8*0=0` |
| ------- | -------- | ------- | ------- | ------- |
| `0*2=0` | `2*2=2`  | `4*2=8` | `6*2=12` | `8*2=16` |
| `0*4=0` | `2*4=8`  | `4*4=16` | `6*4=24` | `8*4=32` |
| `0*6=0` | `2*6=12` | `4*6=24` | `6*6=36` | `8*6=48` |
| `0*8=0` | `2*8=16` | `4*8=32` | `6*8=48` | `8*8=64` |

- C語言版本
```c=
#include <stdio.h>
#include <math.h>

int main(int argc, char *argv[]) {
	int i, j;
	for(i = 0; i < 9; i+=2){
		for(j = 0; j < 9; j+=2){
			printf("%d*%d=%2d  ", i, j, i*j);
		}
		printf("\n");
	}
}
```
:::

:::spoiler {state="close"} P5-58 Q4
> 題目說明: 使用迴圈計算1^1+2^2+3^3+...+n^n的值(n由使用者輸入，n為個位數的正整數)(不得使用公式，也不得使用數學函式庫)。
> 不可以使用pow(x, y)
> n = 6
> sum = 50069
- C++語言版本
```cpp=
#include <iostream>
#include <math.h>
using namespace std;

int main(void)
{
	int n;
	long long sum = 0, reg;
	cout << "n=";
	cin >> n;
	
	for(int i = 1; i <= n; i++){
		reg = 1;
		for(int j = 1; j <= i; j++){
			reg *= i;
		}
		sum += reg;
	}
	
	cout << "Sum=" << sum << endl;
}
```
:::

:::spoiler {state="close"} 巢狀迴圈練習
- C++語言版本
```cpp=
#include <iostream>
using namespace std;

int main(void)
{
	cout << "5-1:" << endl;
	for(int i=1; i<=5; i++){
		for(int j=1; j<=i; j++){
			cout << i << " ";
		}
		cout << endl;
	}
	
	cout << endl << "5-2:" << endl;
	for(int i=1; i<=5; i++){
		for(int j=1; j<=6-i; j++){
			cout << i << " ";
		}
		cout << endl;
	}
	
	cout << endl << "5-3:" << endl;
	for(int i=1; i<=5; i++){
		for(int k=0; k<=i; k++){
			cout << " ";
		}
		for(int j=1; j<=6-i; j++){
			cout << i << " ";
		}
		cout << endl;
	}

	cout << endl << "5-4:" << endl;
	for(int i=1; i<=5; i++){
		for(int j=1; j<=5; j++){
			if(i <= j){
				cout << i << " ";
			}else{
				cout << "  ";
			}
		}
		cout << endl;
	}
}
```
:::

:::spoiler {state="close"} 輸入一個身高與體重的範圍，以二維的方式顯示其間的BMI
- C++語言版本
```cpp=
#include <iostream>
#include <iomanip>
using namespace std;

int main(void)
{
	int min_kg, max_kg, min_cm, max_cm;
	cout << "輸入最小體重(kg)= ";
	cin >> min_kg;
	cout << "輸入最大體重(kg)= ";
	cin >> max_kg;
	cout << "輸入最小身高(cm)= ";
	cin >> min_cm;
	cout << "輸入最大身高(cm)= ";
	cin >> max_cm;
	float result;
	
	cout << setfill(' ') << setw(8) << "kg=";
	for(int i=min_kg; i<=max_kg; i++){
		cout << setfill(' ') << setw(8) << i;
	}
	cout << endl;
	
	for(float j=min_cm; j<=max_cm; j++){
		cout << setfill(' ') << setw(8) << fixed << setprecision(0) << "cm=" << j;
		for(float k=min_kg; k<=max_kg; k++){
			result = k / ((j/100)*(j/100));
			cout << setfill(' ') << setw(8) << fixed << setprecision(1) << result;
		}
		cout << endl;
	}
}
```
:::

### 第13週

:::spoiler {state="close"} 以條件迴圈完成級數一 s=1^2+2^2+3^2+...+n^2
- C++語言版本
```cpp=
#include <iostream>
using namespace std;

int main (void)
{
	int n;
	while(cin >> n){
		int sum = 0;
		for(int i=1; i<=n; i++){
			sum += i * i;
		}
		cout << sum << endl;
	}
}
```
:::

:::spoiler {state="close"} N!=1*2*...*N，請問N!不大於10000的最大N為何?
- C++語言版本
```cpp=
#include <iostream>
using namespace std;

int main (void)
{
	int i = 1, sum;
	while(sum < 10000){
		sum *= i;
		i++;
	}
	cout << i-1 << endl;
}
```
:::

:::spoiler {state="close"} 級數一 s=1^2+2^2+3^2+...+n^2，當n為多少時，s會大於5000?
- C++語言版本
```cpp=
#include <iostream>
using namespace std;

int main (void)
{
	int i = 1, sum = 0;
	while(sum < 5000){
		sum += i * i;
		cout << sum << endl;
		i++;
	}
	cout << i << endl;
}
```
:::

:::spoiler {state="close"} P5-59 Q14
- C++語言版本
```cpp=
#include <iostream>
using namespace std;

int main (void)
{
	int buy, income, result;
	int coin_type[4] = {1, 5, 10, 50};
	cout << "欲購票的金額 >> "; 
	cin >> buy;
	
	cout << "請投入百鈔 >> "; 
	while(cin >> income){
		if(income < buy){
			cout << "輸入錯誤請重新輸入。" << endl;
		}else{
			break;
		}
	}
	
	result = income - buy;
		
	for(int i = 3; i >= 0; i--){
		int value = result / coin_type[i];
		result -= value * coin_type[i];
		cout << "找錢(面額:" << coin_type[i] << ") " << value << "個" << endl;
	}
}
```
:::

:::spoiler {state="close"} 有一條繩子長50公尺，每次剪掉一半，剪幾次後，會小於2公尺?
- C++語言版本
```cpp=
#include <iostream>
using namespace std;

int main (void)
{
	float line = 50, round = 0;
	while(line > 2){
		line /= 2;
		round++;
	}
	cout << round << endl;
}
```
:::

:::spoiler {state="close"} 用條件迴圈判斷n是否為質數，方法如作答說明
- C++語言版本
```cpp=
#include <iostream>
using namespace std;

int main (void)
{
	int n;
	while(cin >> n)
	{
		int count = 0;
		int i = 1;
		while(i<=n){
			if(n % i == 0) count += 1;
			if(count > 2) break;
			
			i++;
		}
		
		(count != 2)?
		 	cout << "非質數" << endl
		:
		 	cout << "質數" << endl
		;
	}
}
```
:::

:::spoiler {state="close"} 2是第一個質數，第100個質數是多少?
- C++語言版本
```cpp=
#include <iostream>
using namespace std;

int main (void)
{
	int i = 2;
	int round = 0;
	int memory = 0;
	while(1)
	{
		int count = 0;
		for(int j = 1; j <= i; j++){
			if(i % j == 0) count += 1;
		}
		
		if(count == 2){
			round += 1;
			memory = i;
			if(round == 100) break;
		} 
		i++;
	}
	cout << memory << endl;
}
```
:::
註：將x開根號的原因，比根號x大與其相乘的數，絕對不會是整數。
### 第14週

:::spoiler {state="close"} 輸入十個成績，輸出總分、平均成績、及格人數、不及格人數。
- C++語言版本
```cpp=
#include <iostream>
#define people 10
using namespace std;

int main(void){
	int score[people] = {0};
	
	for(int i=0; i<people; i++){
		cout << "請輸入第" << (i+1) << "位同學的成績 >> "; 
		cin >> score[i];
	}
	
	int sum = 0, average = 0, pass = 0, nopass = 0;
	for(int i=0; i<people; i++){
		sum += score[i];
		(score[i] >= 60)? pass += 1 : nopass += 1;
	}
	average = sum / people;
	
	cout << "總分: " << sum << endl;
	cout << "平均: " << average << endl;
	cout << "及格人數: " << pass << endl;
	cout << "不及格人數: " << nopass << endl;
}
```
:::

:::spoiler {state="close"} 輸入十個成績，輸出標準差。
- C++語言版本
```cpp=
#include <iostream>
#include <cmath>
#define people 10
using namespace std;

int main(void){
	int score[people] = {0};
	int sum = 0, average = 0, sd = 0;
	
	for(int i=0; i<people; i++){
		cout << "請輸入第" << (i+1) << "位同學的成績 >> "; 
		cin >> score[i];
		sum += score[i];
	}
	average = sum / people;
	
	for(int i = 0;i < people;i++){
	   sd += (score[i] - average) * (score[i] - average);
	}
	
	sd /= people;
	sd = sqrt(sd);
	cout << "標準差: " << sd << endl;
}
```
:::

### 第15週

:::spoiler {state="close"} 參照資料，用基本的氣泡排序法，將成績排序。
```cpp=
#include <iostream>
using namespace std;

int bubbleSort(int array[], int size, int sortType)
{
	int count = 0;
	int switchCount = 0;
	
	for(int i = 0; i < size; i++){
		for(int j = 0; j <= (i-1); j++){
			count++;
			// > is DESC
			// < is ASC
			if(sortType == 1){
				if(array[i] < array[j]){
					switchCount++;
					int temp = array[i];
					array[i] = array[j];
					array[j] = temp;
				}
			}else{
				if(array[i] > array[j]){
					switchCount++;
					int temp = array[i];
					array[i] = array[j];
					array[j] = temp;
				}
			}
		}
	}
	// print
	cout << "--- Result ---" << endl;
	cout << "計算次數: " << count << endl;
	cout << "交換次數: " << switchCount << endl;
	for(int k = 0; k < 15; k++){
		cout << array[k] << " ";
	}
	cout << endl << endl;
}

int main(void){
	int sc[] = {60,55,70,80,76,90,91,73,88,73,77,80,85,88,95}; 
	int sc_2[] = {10,20,30,40,50,55,60,65,70,75,80,85,90,95,100};
	
	// ASC = 1, DESC = 0
	bubbleSort(sc, 15, 1);
	bubbleSort(sc, 15, 0);
	bubbleSort(sc_2, 15, 1);
	bubbleSort(sc_2, 15, 0);
}
```
:::

:::spoiler {state="close"} 參照資料，用課本的氣泡排序法，將成績排序。
- C++語言版本
```cpp=
#include <iostream>
using namespace std;

int bubbleSort_book(int array[], int size, int sortType)
{
	int count = 0;
	int switchCount = 0;
	int k = size-1;
	while(k != 0){
		int times = 0;
		for(int i = 0; i <= (k-1); i++){
			count++;
			if(sortType == 1){
				if(array[i+1] < array[i]){
					switchCount++;
					int temp = array[i];
					array[i] = array[i+1];
					array[i+1] = temp;
					times = i;
				}
			}else{
				if(array[i] < array[i+1]){
					switchCount++;
					int temp = array[i];
					array[i] = array[i+1];
					array[i+1] = temp;
					times = i;
				}	
			}
		}
		k = times;
	}
	
	cout << "--- Result ---" << endl;
	cout << "計算次數: " << count << endl;
	cout << "交換次數: " << switchCount << endl;
	for(int i=0; i<size; i++){
		cout << array[i] << " ";
	}
	cout << endl << endl;
}

int main(void){
	int sc[15] = {60,55,70,80,76,90,91,73,88,73,77,80,85,88,95};
	int sc_2[15] = {10,20,30,40,50,55,60,65,70,75,80,85,90,95,100};
	
	bubbleSort_book(sc, 15, 1); 
	bubbleSort_book(sc, 15, 0); 
	bubbleSort_book(sc_2, 15, 1);
	bubbleSort_book(sc_2, 15, 0);
}
```
:::
:::spoiler {state="close"} 二維陣列應用--公司營業額
- C++語言版本
```cpp=
#include <iostream>
#include <iomanip>
#include <cmath>
#include <string>

#define LENGTH 11 

using namespace std;

void printThousand(int number){
	// count
	int count = 0, n = number, space = 12;
	while(n>0){
		n /= 10;
		count++;
	}
	
	space -= count + ceil(count/3);
	for(int i = 0; i < space; i++){
		cout << " ";
	}
	
	for(int i = count-1; i > 0; i--){
		cout << (int)(number / pow(10,i));
		number -= (int)(number / pow(10,i)) * pow(10,i);
		if(i % 3 == 0) cout << ",";
	}
	cout << number % 10;
}

int main(void)
{
	string dataViewRow[6] = {"", "Season 1", "Season 2", "Season 3", "Season 4", "Total"};
	string dataViewCol[4] = {"Branch A", "Branch B", "Branch C", "Sum"};
	
	int company[4][5] = {
		{123024, 183091, 181402, 193031, 0},
		{275924, 219848, 120985, 218994, 0},
		{126712, 193017, 119362, 248916, 0},
		{0, 0, 0, 0, 0},
	};
	
	// counting
	for(int i = 0; i < 3; i++){
		for(int j = 0; j < 4; j++){
			company[i][4] += company[i][j];
		}
	}
	for(int i = 0; i < 5; i++){
		for(int j = 0; j < 3; j++){
			company[3][i] += company[j][i];
		}
	}
	
	// print
	for(int i = 0; i < 6; i++){
		cout << setw(LENGTH) << dataViewRow[i];	
	}
	cout << endl;
	for(int i = 0; i < 4; i++){
		for(int j = 0; j < 5; j++){
			if(j == 0) cout << setw(LENGTH) << dataViewCol[i];
			printThousand(company[i][j]);
		}
		cout << endl;
	}
}
```
:::

### 第16週

:::spoiler {state="close"} P5-40 Q2 轉置矩陣
- C++語言版本
```cpp=
#include <iostream>
using namespace std;

int main(void)
{
	int x, y;
	cout << "請輸入原始矩陣的行數=>";
	cin >> x;
	cout << "請輸入原始矩陣的行數=>";
	cin >> y;
	
	if(x <= 10 && y <= 10){
		int A[y][x] = {0};
		
		for(int i = 0; i < y; i++){
			for(int j = 0; j < x; j++){
				cout << "A[" << i << "][" << j << "]元素值=>";
				cin >> A[i][j];
			}
		}
		
		cout << "原始陣列" << endl;
		for(int a = 0; a < y; a++){
			for(int b = 0; b < x; b++){
				cout << A[a][b] << "  ";
			}
			cout << endl;
		}
		
		cout << "轉置陣列" << endl;
		for(int a = 0; a < x; a++){
			for(int b = 0; b < y; b++){
				cout << A[b][a] << "  ";
			}
			cout << endl;
		} 
	}
} 
```
:::

:::spoiler {state="close"} P6-40 Q3 矩陣相乘
- C++語言版本
```cpp=
#include <iostream>
using namespace std;

int main(void)
{
	int m1[2][3] = {
		{1, 2, 3},
		{4, 5, 6}
	};
	int m2[3][2] = {
		{1, 2},
		{3, 4},
		{5, 6},
	};
	int m3[2][2] = {0};
	
	for(int i = 0; i < 2; i++){
		for(int j = 0; j < 2; j++){
			for(int k = 0; k < 3; k++){
				m3[i][j] = m3[i][j] + m1[i][k] * m2[k][j];
			}
		}
	}
	
	cout << "-- m1 --" << endl;
	for(int i = 0; i < 2; i++){
		for(int j = 0; j < 3; j++){
			cout << m1[i][j] << " ";
		}
		cout << endl;
	}
	
	cout << "-- m2 --" << endl;
	for(int i = 0; i < 3; i++){
		for(int j = 0; j < 2; j++){
			cout << m2[i][j] << " ";
		}
		cout << endl;
	}
	
	cout << "-- m3 --" << endl;
	for(int i = 0; i < 2; i++){
		for(int j = 0; j < 2; j++){
			cout << m3[i][j] << " ";
		}
		cout << endl;
	}
} 
```
:::

:::spoiler {state="close"} P6-40 Q1 
- C++語言版本
```cpp=
#include <iostream>
#include <string>

#define LENGTH 3
using namespace std;

int main(void)
{
	string input;
	string contact[LENGTH][2] = {
		{"大雄", "032125678"},
		{"宜靜", "0226713456"},
		{"技安", "075534321"},
	};
	int find = 0;
	cout << "請輸入要查詢的對象:";
	cin >> input;
	
	for(int i = 0; i<LENGTH; i++){
		if(input == contact[i][0]){
			find = 1;
			cout << "電話是:" << contact[i][1];
			break;
		}
	}
	
	if(!find) cout << "查無此人";
}
```
:::

:::spoiler {state="close"} P6-41 Q6
- C++語言版本
```cpp=
#include <iostream>
#include <string>

using namespace std;

int main(void)
{
	string input, search, rem;
	int counter = 0;
	
	cout << "請輸入字串(字串長度<100):";
	cin >> input;
	if(input.length() < 100){
		cout << "請輸入尋找字元:";
		cin >> search;
		
		for(int i = 0; i<input.length(); i++){
			if(rem.assign(input,i,1) == search) counter += 1;
		}
		
		cout << "字串" << input << "中有 " << counter << " 個 " << search << " 字元";	
	}
}
```
:::
:::spoiler {state="close"} P6-41 Q8
- C++語言版本
```cpp=
#include <iostream>
#include <string>

using namespace std;

int main(void)
{
	string input;
	cin >> input;
	
	for(int i=0; i<input.length(); i++){
		int code = (int)input[i];
		
		if(code >= 65 && code <= 90){
			cout << (char)(code + 32);
		}else if(code >= 97 && code <= 122){
			cout << (char)(code - 32);
		}else{
			cout << "?";
		}
	}
}
```
:::
### 第17週(期末考上屆考題)

:::spoiler {state="close"} 期末考第一題
- C++語言版本
```cpp=
#include <iostream> 
#include <string>

using namespace std;

int main(void)
{
	long long money, pay;
	
	cout << "輸入$$"; 
	cin >> money;
	
	int days = 0;
	while(days < 30)
	{
		(days == 1)? pay = 1: pay *= 2;
		money -= pay;
		if(money < 0){
			break;
		}
		days++;
	}
	
	if(money > 0){
		cout << "富翁在30天過後還剩餘"  << money << endl;
	}else{
		cout << "富翁在第" << days << "天破產" << endl;
	}
}
```
:::

:::spoiler {state="close"} 期末考第二題
- C++語言版本
```cpp=
#include <iostream> 
#include <string>

#define LENGTH 20

using namespace std;

int main(void)
{
	int sum;
	float average;
	int score[20] =
	{50,60,90,88,75,84,66,93,52,73,58,96,84,77,72,40,89,63,68,79};
	
	for(int i = 0; i < LENGTH; i++){
		for(int j = 0; j < i-1; j++){
			if(score[i] > score[j]){
				int temp = score[i];
				score[i] = score[j];
				score[j] = temp;
			}
		}
	}
	
	sum = 0;
	for(int i = 0; i < 5; i++){
		sum += score[i];
	}
	average = (float)sum/5;
	cout << "頂標為" << average << endl; 
	
	sum = 0;
	for(int i = 0; i < 10; i++){
		sum += score[i];
	}
	average = (float)sum/10;
	cout << "高標為" << average << endl; 
	
	sum = 0;
	for(int i = 0; i < 20; i++){
		sum += score[i];
	}
	average = (float)sum/20;
	cout << "均標為" << average << endl; 
}
```
:::

:::spoiler {state="close"} 期末考第三題
- C++語言版本
```cpp=
#include <iostream> 
#include <string>

#define LENGTH 7
#define ROW 3

using namespace std;

int main(void)
{
	string books[LENGTH][ROW] = {
		{"張三", "C", "P101"},
		{"李四", "R", "P131"},
		{"王五", "R", "P211"},
		{"張三", "Python Programming", "P205"},
		{"張三", "Java Practice", "P330"},
		{"王五", "C", "P774"},
		{"李四", "C", "P311"},
	};
	
	string input;
	getline(cin, input); // ** read all line 
	
	for(int i = 0; i < LENGTH; i++){
		if(books[i][1] == input){
			cout << books[i][0] << " " << books[i][1] << " " << books[i][2] << endl;
		}
	}
}
```
:::
___
### 第18週(期末考週)

:::spoiler {state="close"} 期末作業-萬年曆
- C++語言版本
```cpp=
#include <iostream>
#include <string>
#include <cmath>
using namespace std;

int leap(int year){
	if(year % 4 == 0){
		if(year % 100 == 0){
			if(year % 400 == 0){
				return 29;
			}else{
				return 28;
			}
		}else{
			return 29;
		}
	}else{
		return 28;
	}
}

int main(void)
{
	int fix_year = 2020, fix_month = 0, fix_days = 3;
	int inputYear, inputMonth, inputLang;
	
	cout << "請選擇語言(0: 繁體中文, 1: 日文, 2: 英文) >> ";
	while(cin >> inputLang){
		if(inputLang == 1 || inputLang == 2 || inputLang == 0){
			cout << "Success." << endl;
			break;
		}else{
			cout << "Retry." << endl;
		}
	}
	cout << "請輸入年份 >> ";
	cin >> inputYear;
	cout << "請輸入月份 >> ";
	cin >> inputMonth;
	
	int monthsDay[12] = {31, 0, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
	string langWeek[3][7] = {
		{"日", "一", "二", "三", "四", "五", "六"},
		{"日", "月", "火", "水", "木", "金", "土"},
		{"Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"},
	};
	
	// count
	int sumDay = 0;
	if(inputYear < fix_year){
		while(1){
			if(fix_month == 1) monthsDay[1] = leap(fix_year);
			fix_month -= 1;
			if(fix_month == -1){ // 跳年 
				fix_year -= 1;
				fix_month = 11;
			}
			
			sumDay += monthsDay[fix_month]; // 累積天數 
			if((inputYear == fix_year) && ((inputMonth-1) == fix_month)) break;
		}
		fix_days -= (sumDay - ((sumDay) / 7) * 7); // 倒敘天數 
		if(fix_days < 0) fix_days += 7; // 跨週則需要補為正數 
		
	}else if(inputYear >= fix_year){
		if(inputYear != fix_year ||  (inputMonth-1) != fix_month){
			while(1){
				if(fix_month == 1) monthsDay[1] = leap(fix_year);
				sumDay += monthsDay[fix_month++];  // 累積天數 
				
				if(fix_month == 12){ // 跨年 
					fix_year += 1;
					fix_month = 0;
				}
				if((inputYear == fix_year) && ((inputMonth-1) == fix_month)) break; // 到該月停止 
			}	
		}
		fix_days = (fix_days + sumDay) % 7;
	}
	
	// print
	cout << endl;
	for(int i = 0; i < 7; i++){
		cout << langWeek[0][i] << " ";
	}
	cout << endl;
	for(int i = 0; i < fix_days; i++){
		cout << "   "; // space 
	}
	int days = 0;
	if(inputMonth == 2) monthsDay[1] = leap(inputYear); // is_LeapYear 
	while(days < monthsDay[inputMonth-1]){
		days++;
		(days<10)? cout << " " << days << " " : cout << days << " ";
		if((days+fix_days) % 7 == 0) cout << endl;
	}
}
```
:::

:::spoiler {state="close"} 期末作業:依本校現況，輸入學號(字串)，輸出該生的學制、科系、班級、座號
![](https://i.imgur.com/QDtOdYH.png)
- C++語言版本
```cpp=
#include <iostream> 
#include <string>
#include <cmath>

using namespace std;
 
int convert_string_to_int(string str){
	int base = 0.0;
	int real = 0;
	for(int i=str.length()-1; i>=0; i--){
		real += ((int)str[i] - 48) * pow(10.0, base);
		base += 1;
	}
	return real;
} 
 
int main(void)
{
	int currentYear = 109;
	string student_number;
	string type[4] = {"日間部", "進修部", "進修學院", "空中學院"};
	string system[8] = {"五專", "二專", "二技", "四技", "", "產業碩士班", "碩士在職專班", "碩士班"};
	string college[6][9] = {
		{"商學院", "國貿", "會資", "保金", "企管", "財稅", "財金", "休閒", "應統"},
		{""},
		{"設計學院", "商設", "多媒", "室設", "品設"},
		{"資訊與流通學院", "資管", "資工", "流管", "資應"},
		{"語文學院", "應英", "應日", "應中"},
		{"中護健康學院", "護理", "美容", "老服"}
	};
	string classes[3][4] = {
		{"甲", "乙", "丙", "丁"}, // 五專 
		{"一", "二", "三", "四"}, // 四技 
		{"A", "B", "C", "D"} // 二技 
	};
	string learning[4] = {"一", "二", "三", "四"};
	// 每個班級50個人
	
	cout << "請輸入台中科技大學10碼學號 > ";
	cin >> student_number;
	if(student_number.length() == 10){
		for(int i = 0; i < 10; i++)
		{
			int index = (int)student_number[i] - 48;
			
			if(i == 0) cout << "學制: " << type[index-1];
			if(i == 1) cout << system[index-1] << endl;
			if(i == 5) cout << "科系: " << college[index][0] << " ";
			if(i == 6){
				cout << college[(int)student_number[i-1]-48][index] << "系" << endl;
				// 學年度解析
				string school_year;
				school_year = school_year.assign(student_number, 2, 3);  
				int year = convert_string_to_int(school_year);
				cout << "班級: " << college[(int)student_number[i-1]-48][index] << learning[currentYear-year];
				
				// 座號 
				string member;
				member = member.assign(student_number, 7, 3); 
				int currentPeople = convert_string_to_int(member);
				
					if(((int)student_number[1] - 49) == 0) cout << learning[currentPeople/50]; // 五專 
					if(((int)student_number[1] - 49) == 2) cout << learning[currentPeople/50]; // 二技 
					if(((int)student_number[1] - 49) == 3) cout << learning[currentPeople/50]; // 四技
					
				cout << endl;
			}
			if(i == 9){
				string number;
				number = number.assign(student_number, 7, 3); 
				cout << "座號: " << convert_string_to_int(number) << endl;
			}
		}	
	}else{
		cout << "格式錯誤" << endl; 
	}
}
```
:::

:::spoiler {state="close"} 期末作業:依本校現況，輸入某生的學制、科系、班級、座號，輸出該生學號
- C++語言版本
```cpp=
#include <iostream> 
#include <string>
#include <cmath>

using namespace std;
 
int main(void)
{
//	輸入某生的學制、科系、班級、座號，輸出該生學號
	int currentYear = 109;
	string type[4] = {"日間部", "進修部", "進修學院", "空中學院"};
	string system[8] = {"五專", "二專", "二技", "四技", "", "產業碩士班", "碩士在職專班", "碩士班"};
	string college[6][9] = {
		{"商學院", "國貿", "會資", "保金", "企管", "財稅", "財金", "休閒", "應統"},
		{"", "", "", "", "", "", "", "", ""},
		{"設計學院", "商設", "多媒", "室設", "品設", "", "", "", ""},
		{"資訊與流通學院", "資管", "資工", "流管", "資應", "", "", "", ""},
		{"語文學院", "應英", "應日", "應中", "", "", "", "", ""},
		{"中護健康學院", "護理", "美容", "老服", "", "", "", "", ""}
	};
	string classes[3][4] = {
		{"甲", "乙", "丙", "丁"}, // 五專 
		{"一", "二", "三", "四"}, // 四技 
		{"A", "B", "C", "D"} // 二技 
	};
	string learning[4] = {"一", "二", "三", "四"};
	
	string code1, code2, code3, code4;
	int code5;
	cout << "請輸入您的類別(日間部、進修部、進修學院、空中學院) > ";
	cin >> code1;
	cout << "請輸入您的學制(五專、二專、二技、四技、產業碩士班、碩士在職專班、碩士班) > ";
	cin >> code2;
	cout << "請輸入您的學院(商學院、設計學院、資訊與流通學院、語文學院、中護健康學院) > ";
	cin >> code3;
	cout << "請輸入您的班級(例:資管一一) > ";
	cin >> code4;
	cout << "請輸入您的座號 > ";
	cin >> code5;
	
	cout << "=======================" << endl;
	
	cout << "您的學號是: " ;
	for(int i = 0; i < 4; i++){
		if(type[i] == code1) cout << (i+1);
	}
	for(int i = 0; i < 8; i++){
		if(system[i] == code2) cout << (i+1);
	}
	// 先判斷班級->年級 
	string student_year;
	student_year = student_year.assign(code4, 4, 2);
		// 中文是兩個字????? 
	for(int i = 0; i < 4; i++){
		if(learning[i] == student_year) cout << currentYear - i;
	}
	int college_type_index = 0;
	for(int i = 0; i < 6; i++){
		if(college[i][0] == code3){
			cout << i;
			college_type_index = i;
		} 
	}
	// 班級 
	string student_class;
	student_class = student_class.assign(code4, 0, 4);
	for(int i = 1; i < 8; i++){
		if(college[college_type_index][i] == student_class) cout << i;
	}
	if(code5 > 100){
		cout << code5;
	}else if(code5 < 10){
		cout << "00" << code5;
	}else{
		cout << "0" << code5;
	}
}
```
:::
___

## 下學期的地獄作業

### 第1週
無。

### 第2週
:::spoiler {state="close"} 閏年函數
- C語言版本
``` c=
//P5-58 Q7 輸入西元年，判斷閏年(用複合條件)

#include <stdlib.h>
#include <stdio.h>

int R(int);
int R(int y) {
	if(((y % 4) == 0) && ((y % 100) != 0) || ((y % 400) == 0)){
		printf("此年閏年");
	}
	
} 
int main() {
	int y;
	printf("請輸入西元年");
	scanf("%d", &y);
	R(y);
    return 0;
}
```

:::


::: spoiler {state="close"} 質數函數
- C語言版本
``` c=
#include<stdio.h>
#include<stdlib.h>

int ans(int x);
int ans(int x) {
	int y, z, time;
	for( y = 1, z = 0; y <= x; y++) {
		if((x % y) == 0){
			z++;
		}
	}
	if(z == 2) {
		printf("%d\t", x);
		time++;
	}
	if(time == 5 ) {
	printf("\n");
	time = 0;
	}
	
}

void main(void) {
	int i;
	for( i = 2; i <= 100; i++) {
		ans(i);
	}
}
```
:::



:::spoiler {state="close"} BMI函數
``` c=

#include <stdio.h>
#include <stdlib.h>

float fun1(float, float, float);
float fun1(float h1, float k1, float bmi) {
	h1 = h1 / 100;
	bmi = k1 / ( h1 * h1 );
    return bmi;
}
int main() {	
	int kgMin, kgMax, highMin, highMax;
	float bmi,h;
    
	printf("輸入身高的範圍,起始值:\n");
	scanf("%d",&highMin);
	printf("最大值:\n");
	scanf("%d",&highMax);
	printf("輸入體重的範圍,起始值:\n");
	scanf("%d",&kgMin);
	printf("最大值\n");
	scanf("%d",&kgMax);
	printf("   kg= ");
	for( int i = kgMin; i <= kgMax; i++ ) {
		printf("%d   ", i);	
	}
	printf("\n");
	for( int i = highMin; i <= highMax; i++) {
		printf("cm=%d ", i);
		for( int j = kgMin; j <= kgMax; j++) {
			bmi = fun1(i, j, bmi);
            printf("%0.1f ", bmi);
		}
		printf("\n");
	}
	printf("\n");
	return 0;
}

```
:::

### 第3週
無。

### 第4週

:::spoiler {state="close"}擲骰子(一)
> 一次擲一顆骰子，擲1000次，紀錄每次所擲出的點數，並列印出(1~6)各種點數的機率。
``` c=
#include <stdlib.h>
#include <stdio.h>
#include <time.h>

void main(void) {
	int times, i, j;
	float p;
	int lotto[1000];
	srand((unsigned) time(NULL));
	for( times = 1; times <= 1000; i++) {
		lotto[times-1] = (rand()%6) + 1;
	}
	for( i = 1; i <= 6; i++){
		p=0;
		for( j = 1; j <= 1000; j++)	{
			if(lotto[j-1] == i)	{
				p++;
			}		
		}
		printf("值出%d的機率為%0.4f\n", j, p/1000);
	}
} 	
```
:::

:::spoiler {state="close"}擲骰子(二)
> 一次擲兩個骰子，點數由兩個骰子相加。 擲1000次，列出各種點數(2~12)出現的機率 (例如1+3、2+2、3+1，都算4點)
```c=
#include <stdlib.h>
#include <stdio.h>
#include <time.h>

void main(void)
void main(void) {
	int times, i, j;
	float p;
	int lotto[1000];
	srand((unsigned) time(NULL));
	for( times = 1; times <= 1000; i++) {
		lotto[times-1] = (rand()%6) + 1;
//		printf("第%d次擲骰子的值%d\n",i,lotto[i-1]);
	
	}
	
	for( i = 1; i <= 12; i++)	{
			p=0;
			for( j = 1; j <= 1000; j++)	{
				if(lotto[j-1] == i)	{
					p++;
				}
				
			}
			printf("值出%d的機率為%0.4f\n", j, p/1000);
		}
} 	
} 	
```
:::

:::spoiler {state="close"} 引數傳遞:陣列的最大值最小值函式；亂數
``` c=
//引數傳遞:陣列的最大值最小值函式；亂數
#include <stdio.h>
#include <stdlib.h>
#include <math.h>

int Max(int A, int max);
int Max(int A, int max) {
	if(max <= A) {
		max = A;
        return max;
	}
}
int Min(int A, int min);
int Min(int A, int min) {
	if(min >= A) {
		min = A;
        return min;
	}
    
}
int main() {
	int s[20], i = 0, max, min, times;
	srand((unsigned) time(NULL));
	float avg, r;
	for( i = 0; i < 20; i++) {
		s[i] = rand() % 101;
		printf("%d\n",s[i]);
		max = Max(s[i], max);
	}	
	min = s[0];
	for( i = 0; i < 20; i++) {
		min = Min(s[i], min);
	}
	printf("最大值:%d\n", max);
	printf("最小值:%d\n", min);
    
    return 0;
}
```

:::

:::spoiler {state="close"} 引數傳遞:陣列的平均值及標準差函式；亂數
``` c=
//陣列的平均值及標準差函式；亂數
#include <stdio.h>
#include <stdlib.h>
#include <math.h>

float avg2(float sum, float i);
float avg2(float sum, float i) {
	float avg;
	avg = sum / i;
    return avg;
}

float r2(float s,float avg);
float r2(float s,float avg) {
	int r;
	r = ( s - avg ) * ( s - avg );
	return r;
}
int main()
{
	int s[20], sum = 0, i = 0;
	srand((unsigned) time(NULL));
	float avg, r;
	for( i = 0; i < 20; i++)
	{
		
		s[i] = (rand()%11) + 50;
		sum = sum + s[i];
	}
	printf("總和%d\n", sum);
	avg = avg2(sum, i);
	printf("平均值%0.2f\n", avg);
	
	for( i = 0; i < 20; i++)
	{
		r = r + r2(s[i], avg);
	}
	r = sqrt( r / 20 );
	printf("標準差%0.4f\n", r);
	
    return 0;
}
```

:::

### 第5週
:::spoiler {state="close"} 引數傳遞:陣列的排序函數與搜尋函數
``` c=
/* 引數傳遞:陣列的排序函數與搜尋函數 */ 

#include<stdio.h>
#include<stdlib.h>
#include<time.h>

int Sort(int *arr, int sum) {
	int swap, k, i;
	for( k = sum - 1; k > 0; k--) {
			for( i = 0; i < k; i++) {
					if(arr[i] > arr[i+1])
						{
							swap = arr[i];
							arr[i] = arr[i+1];
							arr[i+1] = swap;
						}
				}
		}

	return 1;
} 

int Search(int target,int *arr, int sum) {
/*	int i;									//循序搜尋法 
	for(i=0;i<sum;i++)
		{
		if(arr[i]==target)return i;
		}	
*/ 
	int low = 0, top, i;						//二元搜尋法 
	top = sum - 1;
	while(low <= top)
	{
		i =( low + top) / 2;
		if(arr[i] == target) return i;
		
        else {
			if( arr[i] > target ) top = i - 1;
			
            else low = i + 1;
		}
	}	
	
	 return -1;
} 

void main() {
	int value[20], sum=20, i, j, FindNumber, location, sequence, used;
	srand((unsigned) time(NULL));
	for( i = 0; i < sum; i++)
	{	
		value[i] = (rand()%30) + 1;
		for( j = 0; j < i; j++)
			{
				while(value[i] == value[j])
				{
					i = i - 1;
				}
			}
		
		
	}
		
	sequence = Sort(value, sum);
			
	printf("value[20]=");
	for( i = 0; i < sum; i++) {
			printf(" %d", value[i]);
		}
	printf("\n");

	
	printf("請輸入您要找的數值(1-30):");
	scanf("%d", &FindNumber);
	
	location = Search(FindNumber, value, sum);
	
	if( location == -1 ) printf("在陣列中找不到你輸入的數值");
	else printf("你輸入的數值%d位於value[%d]\n", FindNumber, location);
	system("pause");
}
```
:::

:::spoiler {state="close"} 用遞迴的方式設計N!函式
``` c=
//N!
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int N(int k);
int N(int k) {
	int i, r;
	r = k;
	for( i = 1; i < r; i++) {
		k = k * i;
	}
	return k;
	
}
int main()
{
	int k, n, ans;
	printf("請輸入你要計算的值\n");
	scanf("%d", &k);
	ans = N(k);
	printf("%d", ans);
    
    return 0;
}
```

:::

:::spoiler {state="close"} 用遞迴的方式寫 K的n次方函式
``` c=
//	用遞迴的方式寫 K的n次方函式

#include <stdio.h>
#include <stdlib.h>

int N(int k, int n, int i, int ans);
int N(int k, int n, int i, int ans) {
	if(i<n)	{
		ans = ans * k;
		i++;
		return N(k, n, i, ans); 
	}
	else {
		return ans;
	}
}
int main() {
 	int k, n, i = 0, ans = 1;
 	printf("輸入k\n");
 	scanf("%d", &k);
 	printf("輸入次方n\n");
 	scanf("%d", &n);
 	printf("%d",N(k, n, i, ans));
 	
    return 0;
 }
```

:::

:::spoiler {state="close"} P7-88 Q20
``` c= 
//輾轉相除

#include <stdio.h>
#include <stdlib.h>

int N(int x, int y);
int N(int x, int y) {
	int temp;
	if(x < y) {
		temp = x;
		x = y;
		y = temp;
	}
	x = x % y;
	if(x != 0)
	{
		temp = x;
		x = y;
		y = temp;
	}
	return y;
}
int main() {
 	int x, y;
    
 	printf("輸入x:\n");
 	scanf("%d", &x);
 	printf("輸入y:\n");
 	scanf("%d", &y);
    
 	printf("最大公因數為:%d", N(x, y));
 	
    return 0;
  } 
```

:::

:::spoiler {state="close"} P8-49 Q4
``` c=
/* 	P8-49 Q4 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char *DeleteEmpty(char *str1){
	int len, i, j;
	le n= strlen(str1);
	for( i = 0, j = 0; i < len; i++)
	{
		if(str1[i] != ' ') {
			str1[j++] = str1[i];
		}
	}
	str1[j] = '\0';
	return str1;
	
}

int main(){
	char *str1 = "My dear friend";
	char *str2 = DeleteEmpty(strdup(str1));
	
	printf("str1為:%s\n", str1);
	printf("str2為:%s\n", str2);
    return 0;
}
```
:::

### 第6週
:::spoiler {state="close"} P8-50 Q5
``` c=
#include<stdio.h>

int main() {
	int A[15] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
	int B[15] = {2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30};
	int C[15] = {0};
	int i;
	for( i = 0; i < 15; i++) {
		printf("c=a+b=%d\n", *(A+i) + *(B+i));
	}
    return 0;
}
```

:::
:::spoiler {state="close"} P8-50 Q6
``` c=
/*P8-50 Q6*/ 
 #include <stdio.h>
 #include <stdlib.h>
 
 int main() {
 	int A[3][5] = { {1, 2, 3, 4, 5}, {6, 7, 8, 9, 10}, {11, 12, 13, 14, 15} };
	int B[3][5] = { {2, 4, 6, 8, 10}, {12, 14, 16, 18, 20}, {22, 24, 26, 28, 30} };
	int c[3][5] = {0};
	int i, j;
	
	for( i = 0; i < 3; i++)
	{
		for(j = 0; j < 5; j++)
		{
			c[i][j] = *(*(A+i)+j) + *(*(B+i)+j);
			printf("C[%d,%d]=%2d ", i+1, j+1, c[i][j]);
		}
		printf("\n");
        
        return 0;
	}
 }
```
:::
:::spoiler {state="close"} P8-51 Q7
``` c=
/* P8-50 Q5*/

#include<stdio.h>

int main()
{
	int *A;
	int *B;
	int *C;
	int i, j;
	printf("請輸入列數:");
	scanf("%d", &j);
	
	A = malloc( sizeof(int) * j);
	B = malloc( sizeof(int) * j);
	C = malloc( sizeof(int) * j);
	
	srand((unsigned) time(NULL));
	
	for( i = 0; i < j; i++)
	{
		*(A+i) = (rand()%100) + 1;
		printf("A[%d]的值為:%d\n", i+1, *(A+i));
		*(B+i) = (rand()%100)+1;
		printf("B[%d]的值為:%d\n", i+1, *(B+i));
		*(C+i) = *(A+i) + *(B+i);
	}
	
	
	for( i = 0; i < j; i++)
	{
		printf("C[%d]=%d \n", i+1, *(C+i));
	}
	
	free(A);
	free(B);
	free(C);
    return 0;
 
}
```
:::

### 第7週
:::spoiler {state="close"} P8-52 Q8
``` c=
/* P8-50 Q5*/

#include<stdio.h>

int main() {
	int *A;
	int *B;
	int *C;
	int i, j, m, n;
	
	printf("請輸入矩陣大小\n");
	printf("請輸入列數:");
	scanf("%d", &m);
	printf("請輸入行數:");
	scanf("%d", &n);
	
	A = malloc( sizeof(int) *m *n);
	B = malloc( sizeof(int) *m *n);
	C = malloc( sizeof(int) *m *n);
	
	srand((unsigned) time(NULL));
	
	for( i = 0; i < m; i++) {
		for( j = 0; j < n; j++) {
		*((A+i)+j) = (rand()%100) + 1;
		printf("A[%d,%d]的值為:%3d   ", i+1, j+1, *((A+i)+j));
		*((B+i)+j) = (rand()%100) + 1;
		printf("B[%d,%d]的值為:%3d   ", i+1, j+1, *((B+i)+j));
		*((C+i)+j) = *((A+i)+j) + *((B+i)+j);
		printf("C[%d,%d]=%3d\n", i+1, j+1, *((C+i)+j));
		}
	}

	free(A);
	free(B);
	free(C);
    return 0;
 } 
```
:::
:::spoiler {state="close"} P9-32 Q1

:::
:::spoiler {state="close"} P9-32 Q2

:::
:::spoiler {state="close"} P9-33 Q3

:::

### 第8週
:::spoiler {state="close"} P10-53 Q1，但在程式中給定10筆資料，不要由使用者輸入
``` c=
/* P10-53 Q1*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct book {
	char edit[6] ;
	char name[20] ;
	char house[20] ;
	char ISBN[14] ;
 };
 
int main() {
	int i;
	struct book bo[10];
	for(i = 0; i < 10; i++) {
		strcpy(bo[i].edit,"陳錦輝");
		strcpy(bo[i].name,"JAVA");
		strcpy(bo[i].house,"台中出版社");
		strcpy(bo[i].ISBN,"123456789");
		printf("%s\t%s\t%s\t%s\t\n",bo[i].edit,bo[i].name,bo[i].house,bo[i].ISBN);
	}
	return 0;
 }
```
:::
:::spoiler {state="close"} P10-54 Q3
``` c=
/* P10-54 Q3*/
#include <stdio.h> 
#include <stdlib.h>
#include <string.h>
#include <math.h>

struct point {
	int x;
	int y;
};

float distance(int a,int b) {
	float d;
	d = sqrt( ( a * a ) + ( b * b ) );
	return d;
}

int main() {
	struct point z[2];
	int i, x, y;
	float d;
	for( i = 0; i < 2; i++)	{
		printf("請輸入第%d個x\n", i+1);
		scanf("%d", &z[i].x);
		printf("請輸入第%d個y\n", i+1);
		scanf("%d", &z[i].y);
	}
	x = z[0].x-z[1].x;
	y = z[0].y-z[1].y;
	d = distance(x, y);
	printf("%f", d);
	return 0;
}
```
:::
:::spoiler {state="close"} 承Q3的結構，隨機產生1000個點，範圍在+-10之間，統計他們落在四個象限的數量
``` c=
/*承Q3的結構，隨機產生1000個點，範圍在+-10之間，統計他們落在四個象限的數量*/

#include <stdio.h> 
#include <math.h>
#include <time.h>

struct point
{
	int x;
	int y;
};

int main() {
	struct point z[1000];
	int i, x, y;
    int a = 0, b = 0;
    int c = 0, d = 0;
	
	srand((unsigned) time(NULL));
	
	for( i = 0; i < 1000; i++) {
		z[i].x = -(rand()%21) + 10;
		z[i].y = -(rand()%21) + 10;
        int x = z[i].x
        int y = z[i].y
        if(x > 0) {
            if(y > 0) {
                a++;
             } 
            else {
                c++;
            }
        }
        else {
            if(y > 0) {
                b++;
            }
            else {
                d++;
            }
        }
	}
	printf("第一象限: %d 第二象限: %d 第三象限: %d 第四象限: %d", a, b, c, d);
	return 0;
}
```
:::

### 第9/10週(期中考/期中考補考)
:::spoiler {state="close"} 期中考(一)

:::
:::spoiler {state="close"} 期中考(二)

:::
:::spoiler {state="close"} 期中考(三)

:::

### 第11週
無。

### 第12週
無。

### 第13週
:::spoiler {state="close"} P10-54 Q9

:::
:::spoiler {state="close"} P10-54 Q10

:::

### 第14週
:::spoiler {state="close"} P11-31 Q1 資料在程式內給定，不要讓使用者輸入

:::
:::spoiler {state="close"} 將P11-31 Q1產生的文字檔讀出來，顯示在螢幕上

:::

### 第15週
:::spoiler {state="close"} 前十名排行榜

:::

### 第16週
:::spoiler {state="close"} P11-32 Q4

:::
:::spoiler {state="close"} P11-32 Q5

:::
:::spoiler {state="close"} 以物件導向方式重寫P10-16範例ch10_04.c

:::

### 第17週
:::spoiler {state="close"} 以C++語法改寫閏年函數

:::
:::spoiler {state="close"} 以C++語法改寫P8-50 Q6

:::
:::spoiler {state="close"} 以C++語法改寫P8-52 Q8

:::

### 第18週
:::spoiler {state="close"} 期末考

:::

:::spoiler {state="close"} Linked list(樂透開獎)
- C語言版本
```c=
/* node 中間插值 */
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include <time.h>

struct Node
{
	int data;
	struct Node *link;
	
};

typedef struct Node node;
typedef node *nodePointer;

nodePointer GetNode();
void ErrorExit();
nodePointer insertFirst(nodePointer L,int d);
nodePointer last(nodePointer L);
nodePointer insertLast(nodePointer L,int d);
nodePointer insertMid(nodePointer L,int d);

nodePointer GetNode()
{
	nodePointer NewNode;
	NewNode=(nodePointer)malloc(sizeof(node));
	if(NewNode==NULL)
	{
		printf("記憶體不足!");
		exit(1);
	}
	return NewNode;
}

void ErrorExit()
{
	printf("error");
	exit(1);
}

nodePointer insertFirst(nodePointer L,int d)
{
	nodePointer n;
	n=GetNode();
	n->data=d;
	n->link=L;
	L=n;
	return L;
}

nodePointer insertLast(nodePointer L,int d)
{
	nodePointer n,LastNP;
	if(L==NULL)
	{
		L=insertFirst(L,d);
	}
	else
	{
		n=GetNode();
		LastNP=last(L);
		n->data=d;	
		n->link=NULL;
		LastNP->link=n;	
	}
	return L;
}

nodePointer last(nodePointer L)
{
	nodePointer Trace;
	if(L==NULL)ErrorExit();
	Trace=L;
	while(Trace->link!=NULL)
	{
		Trace=Trace->link;
	}
	return Trace;
}


nodePointer insertMid(nodePointer L,int d)
{
	nodePointer n;
	nodePointer m;
	nodePointer visit=NULL;
	n=GetNode();
	visit=L;
	if(d<visit->data)
	{
		n=insertFirst(L,d);
		L=n;
		return L;
	}
	while(d>visit->data)
	{
		m=visit;
		visit=visit->link;
		if(visit==NULL){
			L=insertLast(L,d);
			return L;
		}
	}
	n->data=d;
	n->link=visit;
	m->link=n;
	return L;
	

}


int main()
{
	nodePointer Balls=NULL,visit=NULL;
	int i=0,a=0;
	srand((unsigned) time(NULL));
	Balls=insertLast(Balls,rand()%48+1);
	visit=Balls;
	
	for(i=0;i<5;i++)
	{
		a=rand()%48+1;
		visit=Balls;
		
		while(visit!=NULL)
		{
			if(a!=visit->data)
			{
				visit=visit->link;
			}
			else
			{
				a=rand()%48+1;
			}
		}
		/* Balls=insertLast(Balls,a); */
		if(i==4)/*特別號不排序*/
		{
			Balls=insertLast(Balls,a);
		}
		else{
			Balls=insertMid(Balls,a);
		}
			
		
	}

	printf("開獎球如下(最後一球為特別號):\n");
	visit=Balls;
	while(visit!=NULL)
	{
		printf("%d ",visit->data);
		visit=visit->link;
	}
	return 0;
}
```