【问题标题】:I have just started learning function pointers in C and and was trying to code a program but there seems to be a problem and I can't understand what?我刚刚开始学习 C 中的函数指针,并试图编写程序,但似乎有问题,我不明白是什么?
【发布时间】: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/sz6sjqK36Function pointer parameter without asterisk
  • @JosephSible-ReinstateMonica 有趣。我不知道。

标签: c function-pointers


【解决方案1】:

问题是你基本上是在重复调用euclideanDistance。在main 中,您执行areaOfCircle(x1, x2, y1, y1, fptr(x1, y1, x2, y2)),然后在areaOfCircle 中,您执行(*ed)(x1, y1, x2, y2)。要传递函数指针,您只需像传递任何其他类型的指针一样传递它,而不是使用参数调用它。也就是说,将areaOfCircle(x1, x2, y1, y1, fptr(x1, y1, x2, y2)) 更改为areaOfCircle(x1, x2, y1, y1, fptr)

【讨论】:

  • 感谢所有帮助我完成这个程序的人。除了你们帮助我解决的这些问题之外,我还必须将函数 areaOfCircle 从 int 类型更改为 float。特别感谢@JosephSible-ReinstateMonica 告诉我答案。真的很有帮助。
猜你喜欢
  • 1970-01-01
  • 2023-01-20
  • 1970-01-01
  • 2014-10-22
  • 1970-01-01
  • 1970-01-01
  • 2023-04-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多