简体   繁体   中英

fscanf not reading in random values right?

Im trying to read in some numbers from a file and output the results into another file. Every time I try to do this though I just get random values even for values that I am not modifying. I know it probably has something to do with the way I am reading info but I am not sure. contents of lab4sample.dat

12.4   24.0
 5.6    8.0
7.85   12.0
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
//#define FILE_IN “lab4.dat”
#define FILE_IN "lab4sample.dat"

double areaPolygon(double radius, double nsides);
double perimeterPolygon(double radius, double nsides);

int main(void)
{
     FILE * infile;
     FILE * answer_file;

     double radius;
     double nsides;
     double area;
     double perimeter;

     infile = fopen(FILE_IN,"r");
     if(infile == NULL)
     {
         printf("Error on opening the data file\n");
         exit(EXIT_FAILURE);
     }

     answer_file = fopen("lab4.out","w");
     if(answer_file == NULL)
     {
         printf("Error on opening the output file\n");
         exit(EXIT_FAILURE);
     }

     fprintf(answer_file, "\n  Lab 4.\n\n");
     fprintf(answer_file, "            Number      Perimeter      Area Of  \n");
     fprintf(answer_file, " Radius    Of Sides    Of Polygon      Polygon  \n");
     fprintf(answer_file, "--------   --------   ------------   ----------- \n");

     while((fscanf(infile, "%lf %lf\n",&radius, &nsides))== 2)
     {
         area = areaPolygon(radius,nsides);
         perimeter = perimeterPolygon(radius,nsides);
         fprintf(answer_file,"%5.2f %5.2f %5.2f %5.2f \n",&radius,&nsides,&area,&perimeter);
     }

 }
     fprintf(answer_file,"%5.2f %5.2f %5.2f %5.2f \n",&radius,&nsides,&area,&perimeter);

You're printing the addresses of radius , nsides , area , and perimeter . The & operator takes the address of a variable. You want to print their values .

You're trying to print a pointer as a floating point number (your compiler should be complaining). Change:

fprintf(answer_file,"%5.2f %5.2f %5.2f %5.2f \n",&radius,&nsides,&area,&perimeter);

To:

fprintf(answer_file,"%5.2f %5.2f %5.2f %5.2f \n", radius, nsides, area, perimeter);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM