# Math equations

• 04-04-2003
C-Struggler
Math equations
Hi everyone,

I am working on a program to basically multiply some equations.

For example:

(x + 1) * (x + 1)

How would I code this so that my answer shows

x^2 + 2x + 1

I assume I would have to include math.h?? The equation that I have to do is more complex than this, but I think I can handle it if someone gives me the basics for doing this one. Any help would be appreciated.
• 04-04-2003
Shiro
You want to do symbolic algebra? No, you cannot use math.h for that. You would have to write your own expression evaulation function. First think of how you would do it manually and then implement it in code.

In this it could for example be:

Write it out: x * x + x * 1 + 1 * x + 1 * 1
Combine: x * x + 2 * x + 1
• 04-04-2003
C-Struggler
I tried just doing a test with this code
Code:

y = x * x;
printf("%i", y);

This didn't work. If I used this formula, I would want it to print x^2.
• 04-04-2003
Hammer
What didn't work exactly? Was the correct answer too big for the y variable?
• 04-04-2003
C-Struggler
Currently nothing is assigned to the x value...I'll later want to substitute a number in for x, but not at this stage...When I ran the short code I had above...I got a funky number like y = 65750 or something like that.
• 04-04-2003
Hammer
Well, if you didn't assign anything to x, it will start life with a random (undefined) value, so no suprise you got a wierd answer!

Just do:
Code:

int x = 10;
long int y;
y = x * x;
printf("y = %ld\n", y);

• 04-05-2003
ygfperson
As said before, expression evaluation like you want is not implemented directly in C++. All variables have some value, and they are figured out at run-time.