【发布时间】:2021-06-02 04:09:19
【问题描述】:
所以,我试图编写一个程序,要求用户输入图形的点来计算欧几里得距离,并将其用作半径来给出圆的面积。
这是我的代码:
/*You have to take four points(x1,y1,x2,y2) from the user and use it radius to find area of a circle. To find the distance between these points, you will use the Euclidean distance formula.*/
#include <stdio.h>
#include <math.h>
#define PI 3.14
float euclideanDistance(float x1, float x2, float y1, float y2)
{
float ed = 0;
ed = sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1));
return ed;
}
int areaOfCircle(float x1, float y1, float x2, float y2, float(ed)(float x1, float y1, float x2, float y2))
{
return PI * (*ed)(x1, y1, x2, y2) * (*ed)(x1, y1, x2, y2);
//not sure if it's correct or not. No error squiggles.
}
int main()
{
float x1, y1, x2, y2;
float (*fptr)(float, float, float, float);
fptr = euclideanDistance;
printf("Enter the four points x1,y1,x2,y2 to calculate the Euclidean Distance.\n");
printf("x1:");
scanf("%f", &x1);
printf("y1:");
scanf("%f", &y1);
printf("x2:");
scanf("%f", &x2);
printf("y2:");
scanf("%f", &y2);
;
printf("The euclidean distance is %f", fptr(x1, x2, y1, y2));
printf("The area of the circle which has the above mentioned Euclidean Distance as it's radius is: %f", areaOfCircle(x1, x2, y1, y1, fptr(x1, y1, x2, y2))); //error in this printf.
return 0;
}
这里有两个问题。
我不知道如何使用函数 euclideanDistance 作为 areaOfCircle 中的半径,其次是如何在我的主函数中实现它。
对于第二个问题,在 VS Code 中,它向我显示了错误。
{"message": ""float" 类型的参数与"float (*)(float x1, float y1, float x2, float y2)"类型的参数不兼容"}
请解释我做错了什么并指导我。
【问题讨论】:
-
float(ed)(float x1, float y1, float x2, float y2)那不是函数指针。将其与您在main中定义函数指针的方式进行比较。此外,通常为函数指针定义 typedef 以使其更易于在多个地方使用:typedef float (*ed_func)(float x1, float y1, float x2, float y2);,然后用作ed_func fptr = euclideanDistance; -
@kaylum 尽管缺少
*,但它确实可以用作函数指针:请参阅godbolt.org/z/sz6sjqK36 和Function pointer parameter without asterisk -
@JosephSible-ReinstateMonica 有趣。我不知道。
标签: c function-pointers