一个关于C语言文件输入输出的程序问题 高分悬赏

来源:百度知道 编辑:UC知道 时间:2024/06/23 19:01:06
我的问题是 要从TXT文件中读入两列数据,
(A) (B)
5.5 0.3
6.5 0.14
2.3 0.13
3 0.22
4 0.09
4 0.11
4.3 0.12
6.8 0.08
10 0.19
5.5 0.16
13.4 0.13
15.8 0.17

要求是读入这两列数据,经过程序处理,比如:Z=A*X+B*Y
得到处理后的数据放在一个数组中,通过输出文件输出。
我的程序如下:
#include "stdio.h"
#include<math.h>
void main()
{FILE *in;
FILE *out;
float a[3000],b[3000],c[3000];
float p[3000];
char infile[20],outfile[20];
int i=0,t=0,x=0;

printf("enter the infile name:\n");
scanf("%s",infile);
printf("enter the outfile name:\n");
scanf("%s",outfile);
if((in=fopen(infile,"rb"))!=NULL)/*打开源文件,读取数据*/
{

while(!feof(in))/*检查是否到达文件结尾*/
{
fscanf(in,"%f,%f",&p[x++],&c[t++]);/*将in文件中的实数逐个读入到p数组中*/
}
fclose(in);/*关闭源

第一个问题:
这程序有两个问题:
1. 读入的格式与TXT文件不符。你的TXT是用空格来分隔数字的,而程序却用逗号。
2. 读入的行数没有记录,导致p和c两个数组中,大量空元素也被输出。
程序可以这样改:
#include "stdio.h"
#include<math.h>
void main()
{
FILE *in;
FILE *out;
float a[3000],b[3000],c[3000];
float p[3000];
char infile[20],outfile[20];
int i=0,t=0,x=0;

printf("enter the infile name:\n");
scanf("%s",infile);
printf("enter the outfile name:\n");
scanf("%s",outfile);
if((in=fopen(infile,"rb"))!=NULL)/*打开源文件,读取数据*/
{
int rows = 0;
while(!feof(in))/*检查是否到达文件结尾*/
{
fscanf(in,"%f %f\n",&p[x++],&c[t++]);/*将in文件中的实数逐个读入到p数组中*/
rows ++;
}
fclose(in);/*关闭源文件*/
for(i=0;i<rows;i++)
printf("%f,%f\n",p[i],c[i]);

double a=1.5679,m=1.54543,b=1.08490,n=1.48491,Rw=0.034;
for (i=0;i<rows;i