一个关于C语言文件输出的程序问题

来源:百度知道 编辑:UC知道 时间:2024/05/26 19:03:46
我想实现个功能,请大虾们大力support啊

从外部*.txt中输入,比如*.txt中有内容如下:
5.43
2.45
1.23
2.45
2.34

我要输出第二行a=2.45, 第四行b=2.45, 然后计算 c=a+b=4.9,怎么办啊,

我只会把*.txt的内容全部输出,不会赋值计算,好像它是一个一个字符输出的!

#include "stdio.h"

main()
{
FILE *fp;
float a,b,c;
int count = 0;
float temp;
fp = fopen("1.txt","r");
if (fp == NULL)
{
printf("open file error!\n");
}

while (!feof(fp))
{
fscanf(fp,"%f",&temp);
++count;
if (count == 2)
{
a = temp;
}
else if (count == 4)
{
b = temp;
break;
}
}

fclose(fp);

c = a+b;

printf("%f %f %f\n",a,b,c);
}

如果就这几个数,只要读第二,第四个数,很简单。
用 %*f 格式 跳过第一,第三个数,读完第二,第四个数就可关掉文件。

#include <stdio.h>

void main()
{
FILE *fin;
float a,b,c;

fin = fopen("a.txt","r");
fscanf(fin,"%*f %f %*f %f",&a,&b); //跳过第一,第三个数,读第二第四个数
fclose(fin);
c=a+b;
printf("a=%f\n",a); // 输出a