I am a beginner with c++ and am experimenting with functions. I am trying to create a code that gives you the zero(s) of a cubic functions when you enter the a, b, c, and d values. For some reason it keeps saying there is an error. If anyone knows what is wrong with my code please tell me because I am very confused.
Thanks a lot,
Diego315
code:
#include <iostream>
#include <math.h>
#include <cmath>
using namespace std;
float cubicz (float a, float b, float c, float d)
{
float z =
A few problems... first, I suggest doing the quadratic formula, and being comfortable with that, before you try to tackle the cubic formula. Really.
1. pow() takes in two arguments.
pow(x,y) means xy.
2. ^ does not mean exponentiation in C++, it means XOR (exclusive OR). You shouldn't be using it here.
In other words, pow(b^2) doesn't make any sense. You mean pow(b, 2).
For small integer powers, it is often better to just do multiplication. i.e. do x * x instead of pow(x, 2), but it doesn't actually matter that much for just learning purposes.
jonnin what would be fun is having the output be in symbolic, exact notation :D
It's fun to do for quadratic but it's like 10x more complicated to do for cubic.
A cubic equation has 3 roots (sometimes repeated, and sometimes complex rather than real). I see no evidence in your code that you could return THREE roots, not just one, nor that you are checking for complex roots. You might be trying to reproduce Cardano's original expression (incorrectly), but taking square roots of negative numbers isn't recommended.
There are two common ways of writing the solution of cubic equations: one involving square and cube roots (which is the approach you appear to be taking), the other involving trigonometric functions. The latter is more reliable.
Try to simplify your code - there is a large amount of repetition, and at one point you have SEVEN successive brackets; that makes it unreadable. What you currently have inside a square root should give rise to a discriminant, which - as for a quadratic - will determine if some roots are complex.