我正在为一个必须使用函数的类编写一个程序,我没有得到任何语法错误,并且多次尝试改变事情没有成功。该功能未正确保存到.out文件中。
以下是代码:
/* LAB13, functions */
/* Given the number of sides of an n-side regular polygon */
/* and the radius of the circle, find the perimeter and */
/* area of the polygon */
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define IN_FILE "lab13.dat"
#define OUT_FILE "lab13.out"
/* function prototypes */
double get_perimeter(double n, double radius);
double get_area(double n, double radius);
int main(void)
{
double n; /* number of sides */
double radius; /* radius of the circle */
double area; /* area of the polygon */
double perimeter; /* perimeter of the polygon */
FILE * data_in; /* input file pointer */
FILE * data_out; /* output file pointer */
/* Open the two required files */
data_in = fopen(IN_FILE, "r");
if (data_in == NULL)
{
printf("Error on fopen file %s \n", IN_FILE);
exit(EXIT_FAILURE);
}
data_out = fopen(OUT_FILE, "w");
if (data_out == NULL)
{
printf("Error on fopen file %s \n", OUT_FILE);
exit(EXIT_FAILURE);
}
/* Print headers */
fprintf(data_out, "\nScott _________. Lab13. \n\n");
fprintf(data_out, " Number Of Sides Radius Perimeter Area \n");
fprintf(data_out, " of Polygon of Circle of Polygon of Circle \n");
fprintf(data_out, "---------------- --------- ---------- --------- \n");
while ((fscanf(data_in, "%lf%lf", &n, &radius))== 2)
{
perimeter = get_perimeter(n, radius);
area = get_area(n, radius);
fprintf(data_out,"%8i %17.3f %11.3f %10.3f\n",
n, radius, perimeter, area);
}
printf("\n");
fclose(data_in);
fclose(data_out);
return EXIT_SUCCESS;
}
/*-----------------------------------------------------------*/
double get_perimeter(double n, double radius)
{
double perimeter;
perimeter = 2 * n * radius * (sin(M_PI/n));
return perimeter;
}
/*-----------------------------------------------------------*/
double get_area(double n, double radius)
{
double area;
area = 0.5 * n * (radius*radius) * (sin(2*M_PI)/n);
return area;
}
/*-----------------------------------------------------------*/
它正在抓取的lab13.dat文件是:
3.0 16.5
5.0 9.1
7.0 11.5
The output from running the program
答案 0 :(得分:1)
您正在使用n
格式打印double
%8i
,该格式需要int
。如果要打印double
但禁止任何可能的非整数部分,请使用精度0,如%8.0f
中所示。
答案 1 :(得分:1)
你的问题在于fprintf。
fprintf(data_out,"%8i %17.3f %11.3f %10.3f\n", n, radius, perimeter, area);
我不是你想要的格式说明符,使用f。可能是一个错字