# 706 整數檔案讀寫
```
請撰寫一程式,讓使用者輸入四個整數,並讀取read.txt檔案內容,read.txt檔案中包含多個整數。將輸入值與read.txt檔案中的整數由小而大排序後輸出,並寫入至write.txt檔案。
輸入說明 四個整數,並讀取read.txt檔案內容
輸出說明 排序後的結果,並寫入至write.txt檔案
範例輸入
10 35 60 85
範例輸出
10
35
59
60
62
75
85
90
http://pl-learning-blog.logdown.com/posts/1102314
https://dotblogs.com.tw/0xde/2015/06/03/151471
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define LEN 20
void sort(int*, int);
int main()
{
FILE *fin = fopen("read.txt", "r");
FILE *fout = fopen("write.txt", "a");
char buf[LEN];
int y[LEN];
int i;
for (i=0; i<4; ++i){
scanf("%d", &y[i]);
}
//從檔案讀取字串
while ( fgets(buf, LEN, fin) != NULL){ //每次從fin讀取一行
y[i] = strtol(buf, NULL, 10); //字串轉成數字
i++;
memset(buf, 0, LEN); //清空buf內的資料
}
sort(y, i);
//數字寫入檔案
for (int j=0; j<i; ++j){
sprintf(buf, "%d", y[j]); //數字轉成字串
strcat(buf, "\n");
printf("%s", buf);
fputs(buf, fout); //字串寫入檔案
memset(buf,0,LEN);
}
fclose(fin);
fclose(fout);
}
// size = sizeof(x) / sizeof(x[0])
void sort(int* x, int size){
int max;
for (int k=0; k<size-1; ++k){
for (int i=0; i<size-1; ++i){
if (x[i]>x[i+1]){
max = x[i];
x[i] = x[i+1];
x[i+1] = max;
}
}
}
}
```
# 708 12小時制時間
```
請撰寫一程式,讓使用者輸入三組24小時制的「時」與「分」,將輸入的24小時制時間轉換為12小時制後輸出,並輸出有幾個時間屬於AM時段。
提示:24小時制,「時」的範圍是0 ~ 23、「分」的範圍是0 ~ 59
輸入說明 三組24小時制的「時」與「分」
輸出說明 三組12小時制的時間以及有幾個時間屬於AM時段
範例輸入
0 18
12 5
20 45
範例輸出
AM 12:18
PM 12:5
PM 8:45
1
#include <stdio.h>
#define N 6
void digitalClock(int* y, int n);
int main()
{
int y[N];
for (int i=0; i<N; ++i){
scanf("%d", &y[i]);
}
digitalClock(y, N/2);
}
void digitalClock(int* y, int n){
int j=0, k=0;
for (int i=0; i<n; ++i){
int hour = y[k];
int min = y[k+1];
k+=2;
if (hour<12){
j++;
if (hour==0)
hour=12;
printf("AM %d:%d\n", hour, min);
} else {
if (hour>12)
hour-=12;
printf("PM %d:%d\n", hour, min);
}
}
printf("%d", j);
}
```
# 710 FIFO分頁替換演算法
```
1. 請撰寫一程式,實作FIFO(First in First out)分頁替換演算法,讓使用者輸入十個小於10的正整數,要儲存在四個記憶體空間中,請依序輸出每次經過FIFO演算法後的結果。輸出的每個值請給予兩個欄位寬並靠左對齊,若記憶體空間為Null時,以數字「0」表示。
2. FIFO規則:先進先出法,當記憶體空間滿的時候,會淘汰掉最先進入記憶體的資料。
3. 分頁替換規則:輸入的資料若存在於記憶體空間中,則不動作;反之,則執行 FIFO規則。
輸入說明 十個小於10的正整數
輸出說明 每次經過FIFO分頁替換演算法後的結果
範例輸入
7 5 1 2 5
3 5 4 2 3
範例輸出
7 0 0 0
7 5 0 0
7 5 1 0
7 5 1 2
7 5 1 2
3 5 1 2
3 5 1 2
3 4 1 2
3 4 1 2
3 4 1 2
下圖中的 黃色點 為 空格
#include <stdio.h>
int FIFO(int* x, int a, int k);
int main()
{
int x[4]={0};
int num;
int k=0;
for (int i=0; i<10; ++i){
scanf("%d", &num);
k = FIFO(x, num, k);
printf("%d %d %d %d \n", x[0], x[1], x[2], x[3]);
}
}
int FIFO(int* x, int a, int k){
int j=0;
for (int i=0; i<4; ++i){
if (x[i] == 0){
x[i]=a;
break;
} else {
if (a != x[i]){
j++;
}
}
}
if (j==4){
x[k] = a;
k++;
if (k==4)
k=0;
}
return k;
}
```