Need help on C++ Functions!

Hi guys,

I need help on a task, which deals with functions. I've started on the program itself, but don't quite understand how to use the #define function to calculate using a formula.

Could someone explain how to use the #define statement to calculate something based on an equation they have given? For example. X = 1/2pi(Z)(Y), where the user was asked to input a Z and Y value using cin.

THANKS!
#define is not a function. It is a preprocessor directive. Are you sure you want to use that here?

Well our teacher told us to use the #define statement to calculate for X. Its one of the guidelines. I already got the user input for Z and Y through calling the functions. I'd really appreciate the help!
If you're to use a define statement to calculate something, then it's essentially a macro.

http://www.ebyte.it/library/codesnippets/WritingCppMacros.html
I don't seem to understand this. Could you give me an example? For example, how would i calculate X, with user inputted values of Z and Y using the following formula: X = 1/2pi(Z)(Y)

Thank you!
closed account (o3hC5Di1)
Hi there,

I'm no expert at this, but here's what I think it does.

When you use #define to define a constant variable in your code, all it does is search for every occurrence of that variable identifier and replaces that with its value, i.e.:

1
2
3
4
5
#define PI 3.14
float circle_area;
circle_area = 3*3*PI;
//after preprocessing your last line will basically be
circle_area = 3*3*3.14;


Now, when you use #define for a function (which is then actually called a macro), it will do exactly the same, namely replace your function call with the macro:

1
2
3
4
5
#define calc_circle_area(radius, pi) ((radius)*(radius)*(pi))
float r = 3, circle_area, pi=3.14;
circle_area = calc_circle_area(r,pi);
//after preprocessing your last line will look like this to the compiler:
circle_area = r*r*pi;


So #define coudl be said to only do "search and replace" for the compiler, to give you the option to give certain values or expressions constant names so that your code might be more readable.

If some of the experts around here have any corrections or additions I would myself be most interested to read them.

Hope that helps.

All the best,
NwN
From what I know (also new to this), NwN is correct.

The reason why you do this is because macro's or pre-processor directives don't use up memory the way variables do.

I think what your teacher wants is something like this

1
2
3
4
#define PI =3.14
#define Z "some specified value"
#define Y "other specified value"
#define X (1/2)*PI*Z*Y 
Topic archived. No new replies allowed.