【数据结构】预备练习——文件读写

一、先看题目

使用一个文本文件存储一组数据(x),编程读取数据并计算y=1/(200-x)的值,显示并保存结果,如果是非法操作,输出"Error"。

具体要求:

1 输入数据要典型,有代表性,输入数据类型为float。

2 能够处理错误输入数据,并输出"Error"。

3 使用文本文件作为程序的输入和输出。

文件读写参考:

打开文件
fp=fopen("input.txt","r");

错误判断

cpp 复制代码
if(fp==NULL){
	printf("Not SUCH A FILE:%s",af);
	getch();
	return;
}

读入数据

cpp 复制代码
fscanf(fp,"%d",&num);
fscanf(fp,"%f,%d",&x[i],&y[i]);

打开文件(写文件)
fp=fopen("result.txt","w");

写数据
fprintf(fp,"%d,%.2f,%d,%.2f\n",i,x[i],y[i],b[i]);

下面是程序

cpp 复制代码
#include <iostream>
#include <cstdio>

int writeToFile(int n, FILE *f);
float fx(float x);

int main() {
    const int N = 100;

    // 打开文件并写入数据
    FILE *f = fopen("./input.txt", "w");
    if (f == NULL) {
        std::cerr << "Failed to open input file for writing!" << std::endl;
        return 1;
    }
    
    if (writeToFile(N, f) != 0) {
        std::cerr << "Error writing to file!" << std::endl;
        return 1;
    }

    // 打开文件并读取数据
    FILE *fin = fopen("./input.txt", "r");
    if (fin == NULL) {
        std::cerr << "Failed to open input file for reading!" << std::endl;
        return 1;
    }

    FILE *fout = fopen("./output.txt", "w");
    if (fout == NULL) {
        std::cerr << "Failed to open output file!" << std::endl;
        fclose(fin);
        return 1;
    }

    // 动态分配数组
    float *x = new float[N];
    float *y = new float[N];

    // 读取文件内容并计算
    for (int i = 0; i < N; i++) {
        fscanf(fin, "%f", &x[i]);
        y[i] = fx(x[i]);
    }

    // 将结果写入输出文件
    for (int i = 0; i < N; i++) {
        fprintf(fout, "%f\t%f\n", x[i], y[i]);
    }

    // 关闭文件并释放内存
    fclose(fin);
    fclose(fout);
    delete[] x;
    delete[] y;

    return 0;
}

// 向文件中写数据
int writeToFile(int n, FILE *f) {
    if (f == NULL) {
        std::cerr << "Not SUCH A FILE !" << std::endl;
        return 1;
    }
    for (float x = 0; x < n; x++) { 
        fprintf(f, "%f\n", x);
    }
    fclose(f);
    return 0;
}

// 定义函数 f(x)
float fx(float x) {
    if (x == 200) {
        fprintf(stderr, "Error: division by zero\n");
        return -1;
    } else {
        return 1 / (200 - x);
    }
}
相关推荐
糖葫芦君21 分钟前
Policy Gradient【强化学习的数学原理】
算法
whoarethenext42 分钟前
使用 C++/Faiss 加速海量 MFCC 特征的相似性搜索
开发语言·c++·faiss
向阳@向远方2 小时前
第二章 简单程序设计
开发语言·c++·算法
Mr_Xuhhh3 小时前
信号与槽的总结
java·开发语言·数据库·c++·qt·系统架构
github_czy3 小时前
RRF (Reciprocal Rank Fusion) 排序算法详解
算法·排序算法
liulilittle3 小时前
VGW 虚拟网关用户手册 (PPP PRIVATE NETWORK 基础设施)
开发语言·网络·c++·网关·智能路由器·路由器·通信
许愿与你永世安宁3 小时前
力扣343 整数拆分
数据结构·算法·leetcode
爱coding的橙子3 小时前
每日算法刷题Day42 7.5:leetcode前缀和3道题,用时2h
算法·leetcode·职场和发展
ruanjiananquan994 小时前
c,c++语言的栈内存、堆内存及任意读写内存
java·c语言·c++
满分观察网友z4 小时前
从一次手滑,我洞悉了用户输入的所有可能性(3330. 找到初始输入字符串 I)
算法