quadratic question

write in c++ a statement that evaluates one of the roots of the quadratic equation

i dont know how to start, i am doing the review test, and i am stuck here, any hint on what should i do?

i am a total beginners so i dont know how to add another function (other than main) and only know how to use if and while statements.

thanks
i am a total beginners so i dont know how to add another function


You'll find Lots of answers on Google. And lots of tutorials on Youtube. Explaining the basics of c++, functions, everything.
If you want help on homework, you should try something first. Try using what you know to write something in main().

If you're having trouble with the math, then, first off, here's the formula you should be using:
http://en.wikipedia.org/wiki/Quadratic_formula#/media/File:Quadratic_formula.svg
It solves a quadratic equation of the form ax2 + bx + c = 0.

Define variables for a, b, and c, and a variable for the root's value.
Then, try to translate that picture's equation in valid code in C++.
Your homework only asks you to find one root, so where you see the "plus or minus" symbol, just make that be a +.

The square-root function is sqrt(x) by the way,
put #include <cmath> at the top of your source code to use it.
Last edited on
@Ganado

#include <iostream>
#include <math.h>
#include <cmath>
using namespace std;
int main() {
int a, b, c, sum, total;
cout<<"the root is?"<<endl; //the formula is x^2+bx+c
cin>>a; //1
cin>>b; //-3 is the number i put
cin>>c; //-10
sum=b+((b^2-4(a*c)^1/2)); //i dont know how to write it in c++
total=sum/(2a); //the other part of the formula
cout<<"total is"<<total<<" "; //should of print the answer.. any way i can fix or improve it?
}
Please use code tags <> under the format section for all of your code.

sum = b + ((b ^ 2 - 4(a*c) ^ 1 / 2));

For the b^2. You want the function std::pow.

For example -

1
2
int a = 2, b;
b = std::pow(a, 2);


This will give you b = 4.

total=sum/(2a); Im not sure what you mean by 2a. If you want to multiply 2 and a, then you should already know how to do that since you just did it in the line of code above. (2*a)
Last edited on
Also, be aware of rounding. Unless you have a pleasant numbers for a, b, and c, chances are the root of your equation will not be an integer number - it might something like 3.33 or (1 + sqrt(2)) / 2.

I would instead define your variables as
1
2
int a, b, c;
double sum, total; // floating-point type, for non-integer roots 


In addition, note that directly plugging in (1/2) reduces to 0 due to integer division.
Instead of doing pow(my_variable, 1/2),
you'd have to do either sqrt(my_variable), or pow(my_variable, 1 / 2.0) to force it to do floating-point arithmetic.
Topic archived. No new replies allowed.