Jan 19, 2014 at 7:33pm UTC
Hi all, I was practicing C++ by making the quad formula but for some reasons it gives the wrong answer although the program does run. Help would be appreciated thanks.
#include <iostream>
#include <vector>
#include <math.h>
#include <algorithm>
using namespace std;
void Intro();
int descriminant(int&, int&, int&);
int solve1(int&, int&, int&);
int solve2(int&, int&, int&);
int main()
{
Intro();
int a,b,c;
cout<<"Enter values for a, b and c: ";
cin>>a>>b>>c;
descriminant(a, b, c);
if(descriminant<0){
cout<<"No possible solutions"<<endl;
}
else if(descriminant == 0){
double solution1 = solve1(a, b, c);
cout<<"x = "<<solution1;
}
else{
double solution1 = solve1(a, b, c);
double solution2 = solve2(a, b, c);
cout<<"x= "<<solution1<<", "<<solution2<<", "<<endl;
}
return 0;
}
void Intro(){
cout<<"Hello. This program shall give you answers to quadratics in the form ax^2+bx+c. "<<endl;
}
int descriminant(int& a, int& b, int& c){
int descriminant=((b*b)-(4*a*c));
return(descriminant);
}
int solve1(int& a, int& b, int& c){
return((-1*b) + (sqrt ((b*b)-(4*a*c)))/(2*a));
}
int solve2(int& a, int& b, int& c){
return((-1*b) - (sqrt ((b*b)-(4*a*c)))/(2*a));
}
Jan 19, 2014 at 8:09pm UTC
> return ((-1*b) + (sqrt ((b*b)-(4*a*c)))/(2*a));
lost in stupid parenthesis
Jan 19, 2014 at 9:27pm UTC
For your solve functions, you should be dividing everything by 2*a, not just the root of the discriminant.
1 2 3 4 5 6 7 8
//Your code
return (
(-1*b) //<--This is not divided by 2*a
+ ( sqrt( (b*b)-(4*a*c) ) / (2*a) )
);
//Rearranged parentheses (among a couple other things)
return ( -b + sqrt(b*b - 4*a*c) ) / (2*a);
Random note:
Have faith in the PEMDAS order.
Edit:
Also, why aren't you returning
float
or
double
?
int
will truncate your answers.
Last edited on Jan 19, 2014 at 9:30pm UTC