C언어 파일입출력 문제

성민개발로그·2021년 10월 18일
0

C언어

목록 보기
9/9

문제1

词典合并

假设有两个词典文本文件8-1-dict1.txt 和8-1-dict2.txt,各自存放了一些英文词条。存放格式为按行存放,每一行一个词条,并已按照英文字母的顺序排列好了序。
请编写一个程序,将这两个词典文件的内容进行合并,并生成一个新的词典文件8-1-dict3. txt 。
要求:(1)在新的词典文件中,各个词条仍然是有序排列的。
(2)如果一个词条既出现在8-1-dict1.txt中,也出现在8-1-dict2.txt 中,它们在新文件中只能出现一次。

#define _CRT_SECURE_NO_WARNINGS   
#include<stdio.h>
#include<string.h>
int main() {
	char words[100][25]={0, 0};
	char words2[100][25] = { 0, 0 };
	char word[25] = { 0 };
	FILE* fp1 = fopen("8-1-dict1.txt", "r");
	FILE* fp2 = fopen("8-1-dict2.txt", "r");
	FILE* fp = fopen("8-1-dict.txt", "w");
	int i = 0;
	int len1,len2,n;
	while (fgets(word, sizeof(word), fp1)) {
		strcpy_s(words[i], 25, word);
		i++;
	}
	while (fgets(word, sizeof(word), fp2)) {
		for (int j = 0; j < i; j++) {
			if (!strcmp(words[j],word)) break;
			if (j == i - 1) {
				strcpy_s(words[i], 25, word);
				i++;
				break;
			}
		}
	}
	for (int j = 0; j < i; j++) {
		 len1 = strlen(words[j]) - 1;
		 int s = 0;
		for (int k = 0; k < i; k++) {
			if (!strcmp(words[j], words[k])) continue;
			len2 = strlen(words[k]) - 1;
			if (len1 > len2) n = len2;
			else n = len1;
			for (int t = 0; t < n; t++) {
				if ((int)words[j][t] > (int)words[k][t]) {
					s++;
					break;
				}
				else if ((int)words[j][t] < (int)words[k][t]) break;
			}

		}
		strcpy_s(words2[s], 25, words[j]);
	}
	for (int j = 0; j < i; j++) {
		printf("%s", words2[j]);
		fprintf(fp, "%s", words2[j]);
     }
	fclose(fp1);
	fclose(fp2);
	fclose(fp);
	return 0;

}

실행결과:

문제2

股票收益统计

一位朋友在证券行业工作,他希望你能帮助他编写一个程序,对客户的股票收益情况进行统计。程序的输入为一个文本文件8-3-stock.txt(数据为模拟数),里面记录了股票的交易信息(最大为1000条)。每条交易信息占用一行,其格式为:交易日期、股票名称、股票数量、买入价格和卖出价格,各数据项之间用一个空格隔开。例如:
2009-04-29 成长科技 1000 17.8 18.3
2009-05-30 长城化工 2000 6.47 7.03
在程序中对这些交易信息进行统计,计算每笔交易的收益情况,并将结果保存在另外一个文件8-3-stat.txt中。新文件中的输出格式为:交易日期、股票名称、资金占用比例、收益率。各内容项之间仍然用空格间隔。
其中,资金占用比例指的是该股票的购买金额与所有股票购买金额之比,
收益率指的是该股票的盈利金额与购买金额之比。

#define _CRT_SECURE_NO_WARNINGS   
#include<stdio.h>
#include<string.h>
int main() {
	FILE* fp1 = fopen("8-3-stock.txt", "r");
	FILE* fp = fopen("8-3-stat.txt", "w");
	char name[1001][20] = { 0,0 };
	int year[1001] = { 0 };
	int money[1001] = { 0 };
	double buy[1001] = { 0 };
	double sell[1001] = { 0 };
	char monthDay[1001][15] = { 0,0 };
	int i = 0;
	int total=0;
	double distribution;
	double profit;
	while (1) {
		fscanf(fp1, "%d%s %s %d %lf %lf", &year[i], monthDay[i], name[i], &money[i], &buy[i], &sell[i]);
		if (!year[i])break;
		printf("%d%s %s %d %lf %lf \n", year[i], monthDay[i], name[i], money[i], buy[i], sell[i]);
		total += money[i];
		i++;
	}
	i = 0;
	while (year[i]) {
		profit = sell[i]/ buy[i];
		distribution = (double)money[i] / (double)total;
		fprintf(fp, "%d%s %s %2lf %lf\n", year[i], monthDay[i], name[i],distribution, profit);
		printf("%d%s %s %2lf %lf\n", year[i], monthDay[i],name[i], distribution, profit);
		i++;

	}

	fclose(fp1);
	fclose(fp);
	return 0;

}

실행화면

0개의 댓글