c - fscanf 没有读取随机值,对吧?

标签 c scanf

我正在尝试从文件中读取一些数字并将结果输出到另一个文件中。每次我尝试这样做时,即使对于我没有修改的值,我也只是得到随机值。我知道这可能与我阅读信息的方式有关,但我不确定。 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);
     }

 }

最佳答案

您正在尝试将指针打印为 float (您的编译器应该会提示)。变化:

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);

关于c - fscanf 没有读取随机值,对吧?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58311683/

相关文章:

c - c文件操作中的段错误

c - 在 C/C++ 中使用标准输入输入

c - 在函数中使用 scanf 输入更新数组元素(使用指针访问)

c - 我无法让错误 "Variable uninitialized"消失

string - golang 扫描字符串或整数

c - 如何将 scanf 用于 char 数组输入?

c++ - 为什么我不能将数组值返回给主函数?

打印元素后崩溃

c - 为什么在下面的编程中结构显示的内存比实际内存少

c - scanf()将新行char留在缓冲区中