Sh Ndrukaj
Sh Ndrukaj

Reputation: 84

How can I pass a function(which has its own parameters) as a parameter in a function?

I'm trying to pass the function that calculates the Values of a quadratic function, as a parameter to a function that calculates the surface under an Interval.

First I'm just trying to figure out how can I pass the parameters of the quadratic to it.

#include<stdlib.h>
#include<stdio.h>

double quadraticf(double x, double y, double z);


double interval_calculator(double(*quad_pnt)(double, double, double));

int main(){

    interval_calculator(quadraticf);
    return 0;
}

double interval_calculator(double (*quad_pnt)(double)){
    quad_pnt(double f, double yg, double zh);
}

double quadraticf(double x, double y, double z){
    printf("%lf, %lf, %lf \n",x,y,z);
}


Upvotes: 1

Views: 58

Answers (1)

Jabberwocky
Jabberwocky

Reputation: 50778

You probably want something like this:

#include <stdlib.h>
#include <stdio.h>

double quadraticf(double x, double y, double z) {
  printf("quadraticf: %lf, %lf, %lf \n", x, y, z);
  return x + y + z;
}

double otherquadraticf(double x, double y, double z) {
  printf("otherquadraticf: %lf, %lf, %lf \n", x, y, z);
  return x * y * z;
}

double interval_calculator(double (*quad_pnt)(double, double, double), double f, double yg, double zh)
{
  return quad_pnt(f, yg, zh);
}

int main() {
  printf("result = %f\n", interval_calculator(quadraticf, 2.0, 3.0, 4.0));
  printf("result = %f\n", interval_calculator(otherquadraticf, 2.0, 3.0, 4.0));
}

Upvotes: 1

Related Questions