代碼如下:
#include <stdio.h>
#define MAX_DOUBLE 1.79769e+308
#define E 3
struct point
{
int x, y;
};
void compress()
{
FILE * fin = fopen("rand.txt", "r");
FILE * fout = fopen("out.txt", "w");
//上門和下門,初始時門是關著的
double up_gate = -MAX_DOUBLE;
double down_gate = MAX_DOUBLE;
//當前資料的上斜率和下斜率
double now_up, now_down;
int data; //當前讀取到的資料
int last_read_data; //當前資料的前一個資料
int last_stored_data; //最近保存的點
//read and save the first data
fscanf(fin, "%d", &last_stored_data);
fprintf(fout, "0 %d ", last_stored_data);
last_read_data = last_stored_data;
int last_stored_t = 0; //最近保存資料的時間,init 0
//回圈處理資料
int t=0;
while(++t, fscanf(fin, "%d", &data) != EOF)
{
now_up = double(data-last_stored_data-E) / (t-last_stored_t);
if(now_up > up_gate)
up_gate = now_up;
now_down = double(data-last_stored_data+E) / (t-last_stored_t);
if(now_down < down_gate)
down_gate = now_down;
if(up_gate >= down_gate)
{
//保存前一個點
fprintf(fout, "%d %d ", t-1, last_read_data);
last_stored_t = t-1; //修改最近保存資料時間點
last_stored_data = last_read_data;
//初始化兩扇門為當前點與上個點的斜率
up_gate = double(data-last_stored_data-E);
down_gate = double(data-last_stored_data+E);
}
last_read_data = data;
}
// sava end point
fprintf(fout, "%d %d ", t-1, last_read_data);
fclose(fin);
fclose(fout);
}
void uncompress()
{
FILE * fin = fopen("out.txt", "r");
FILE * fout = fopen("src.txt", "w");
point a,b;
fscanf(fin, "%d %d", &a.x, &a.y);
while(fscanf(fin, "%d %d", &b.x,&b.y) != EOF)
{
//Step.1
fprintf(fout, "%d ", a.y);
//Step.2
if(a.x+1 != b.x)
{
double k = double(b.y - a.y) / (b.x - a.x); //計算斜率
for(int i=a.x+1; i<b.x; i++)
{
//線性插值求被壓縮掉的資料
fprintf(fout, "%.0lf ", k*(i-a.x) + a.y);
}
}
a.x = b.x;
a.y = b.y;
}
fprintf(fout, "%d ", b.y);
fclose(fin);
fclose(fout);
}
int main(void)
{
compress();
uncompress();
return 0;
}
}
uj5u.com熱心網友回復:
程式為什么在輸入資料結束之后報錯 stream!=NULL,由單步除錯已找到報錯的地方,但是不明白為什么,也不知道,怎么解決,報錯的地方已經標出來了。求解,謝謝!
uj5u.com熱心網友回復:
fopen都不檢查回傳值嗎, IO錯誤的機會實在太多了.uj5u.com熱心網友回復:
新手,不知道怎么改,求大神指點,謝啦uj5u.com熱心網友回復:
while(++t, fscanf(fin, "%d", &data) == 1)Return Value
Each of these functions returns the number of fields successfully converted and assigned; the return value does not include fields that were read but not assigned. A return value of 0 indicates that no fields were assigned. If an error occurs, or if the end of the file stream is reached before the first conversion, the return value is EOF for fscanf or WEOF for fwscanf.
uj5u.com熱心網友回復:
while(++t, fscanf(fin, "%d", &data) == 1)Return Value
Each of these functions returns the number of fields successfully converted and assigned; the return value does not include fields that were read but not assigned. A return value of 0 indicates that no fields were assigned. If an error occurs, or if the end of the file stream is reached before the first conversion, the return value is EOF for fscanf or WEOF for fwscanf.
uj5u.com熱心網友回復:
樓主解決了嗎?轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/109594.html
標籤:數據庫
