比如:如何实现 printf("两圆相交的面积为:%.2f", area); (area经计算得出)的功能。 只是将结果输入到.txt文件,而不是终端上。
代码如下:(该代码在终端上输出,如何改成在文本文件上输出?)
#include<stdio.h>
#include<math.h>
#include<stdlib.h>
#define PI 3.1415926
struct Circle
{
double x;
double y;
double r;
};
struct Circle first, second;
int judge(struct Circle first, struct Circle second)
{
double distance;
distance = sqrt((first.x - second.x) * (first.x - second.x) + (first.y - second.y) * (first.y - second.y));
if (distance > first.r + second.r) //相离
{
return 2;
}
if (distance == first.r + second.r) //相切
{
return 1;
}
if(distance < fabs(first.r - second.r)) //包含
{
return 0;
}
if (distance == fabs(first.r - second.r)) //内相切
{
return -1;
}
if (distance > fabs(first.r - second.r) && distance < first.r + second.r) //相交
{
return -2;
}
}
void printResult(int i, FILE *fp)
{
double s,r;
double distance = sqrt((first.x - second.x) * (first.x - second.x) + (first.y - second.y) * (first.y - second.y));
if (i == 2)
{
printf("这两个圆相离! 圆间距为:%.2f\n", sqrt((first.x - second.x) * (first.x - second.x) + (first.y - second.y) * (first.y - second.y)) - (first.r + second.r));
}
if (i == 1)
{
printf("这两个圆相切!");
}
if (i == 0)
{
r = first.r < second.r ? first.r : second.r;
printf("这两个圆包含! 重合面积为:%.2f", PI * r * r);
}
if (i == -1)
{
r = first.r < second.r ? first.r : second.r;
printf("这两个圆内相切! 重合m面积为:%.2f", PI * r * r);
}
if (i == -2)
{
double ang1 = acos((first.r * first.r + distance * distance - second.r * second.r) / (2 * first.r * distance));
double ang2 = acos((second.r * second.r + distance * distance - first.r * first.r) / (2 * second.r * distance));
s = ang1 * first.r * first.r + ang2 * second.r * second.r - first.r * distance * sin(ang1);
printf("这两个圆相交! 相交面积为:%.2f\n", s );
}
}
int main(void)
{
int i;
FILE* fp;
printf("请输入第一个圆的圆心坐标及其半径(x,y,r):");
scanf_s("%lf,%lf,%lf", &first.x,&first.y, &first.r);
printf("请输入第二个圆的圆心坐标及其半径((x,y),r):");
scanf_s("%lf,%lf,%lf", &second.x, &second.y, &second.r);
i = judge(first, second);
if ((fp = fopen("file47.txt", "w")) == NULL)
{
printf("打开文件失败!\n");
exit(EXIT_FAILURE);
}
printResult(i, fp);
return 0;
}
用 fprintf() 直接代替 printf() 就可以了 fprintf(fp , "两圆相交的面积为:%.2f", area);
其实 printf(“hello, world !\n”) ;
就是 fprintf(stdout , “hello, world !\n”) ;
|