当前位置:网站首页>6-6 batch sum (*)

6-6 batch sum (*)

2022-06-11 17:37:00 Tomatoes_ Menon

Please write a function , Read the sum of real numbers from a file , And write the results to another file .

The function prototype

void BatchAdd(FILE *in, FILE *out);

explain : Parameters in and out Is a pointer to two files . Function from in Read out data in the indicated file , Write results to out In the document in question .

requirement :in There are many lines in the file , Each line contains two real numbers , In space . Function to find the sum of these two real numbers , write in out In file , One result per line .

requirement : The output results are retained 2 Decimal place .

judging procedures

#include <stdio.h>
#include <stdlib.h>

void BatchAdd(FILE *in, FILE *out);

int main()
{
    FILE *in, *out;

    in = fopen("Addition.txt", "r");
    out = fopen("Sum.txt", "w");

    if (in && out)
    {
        BatchAdd(in, out);
    }
    else
    {
        puts(" The file could not be opened !");
    }

    if (in)
    {
        fclose(in);
    }
    if (out)
    {
        fclose(out);
        puts(" File saved successfully !");
    }

    return 0;
}

/*  The code you submit will be embedded here  */

Create a text file in the folder where the program is located “Addition.txt”, Copy the following :

Addition.txt

25.9 8.7
120.9 87.518
12.8 65.2

sample input

( nothing )

sample output

 File saved successfully !

After program running , open “Sum.txt” file , View file contents .

34.60
208.42
78.00
void BatchAdd(FILE *in, FILE *out)
{
   int i;
    double a,b;
    
    
    while(fscanf(in,"%lf %lf",&a,&b)!=EOF)// Read once print once , Pay attention to accuracy 
    {
        fprintf(out,"%.2lf\n",a+b);
    }
    

}

 

原网站

版权声明
本文为[Tomatoes_ Menon]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/162/202206111717105896.html