0

I am starting to learning C++ and am trying some simple examples. However the example below gives me the following error:

main.cpp:20:32: error: ‘_cal_order’ was not declared in this scope
     double pos=_cal_order(p,n,l); 

I am just trying to pass 3 variables to a function and return a double result. Here is the code:

#include<math.h>
#include <iostream>

using namespace std;

    
int main()
{
    int n = 5000;
    double p = 45000.0;
    double l = 0.001;
    
    double pos=_cal_order(p,n,l);
    cout<<pos<<endl;
        
}; 

double _cal_order(double p, int n, double l)
{
    return static_cast<double>(round(n/(p*l)))*l;
};
halfer
  • 19,824
  • 17
  • 99
  • 186
Stacey
  • 4,825
  • 17
  • 58
  • 99

1 Answers1

2

You must declare the function before using it.

Option 1: Define it first

#include<math.h>
#include <iostream>

using namespace std;


double _cal_order(double p, int n, double l)
{
    return static_cast<double>(round(n/(p*l)))*l;
};
    
int main()
{
    int n = 5000;
    double p = 45000.0;
    double l = 0.001;
    
    double pos=_cal_order(p,n,l);
    cout<<pos<<endl;
        
};

Option 2: Declare it first, define it later

#include<math.h>
#include <iostream>

using namespace std;


double _cal_order(double p, int n, double l);
    
int main()
{
    int n = 5000;
    double p = 45000.0;
    double l = 0.001;
    
    double pos=_cal_order(p,n,l);
    cout<<pos<<endl;
        
};

double _cal_order(double p, int n, double l)
{
    return static_cast<double>(round(n/(p*l)))*l;
};
Iván
  • 971
  • 6
  • 20
  • 1
    Personal opinion: I prefer Option 1. Option 2 requires you to make two changes, one to the forward declaration and one to the function definition, if the function prototype changes. If you change only one you will typically get either a compiler error or a linker error resulting from the mismatch. – user4581301 Sep 08 '21 at 21:23