So I've got my program to the point where it compiles, but upon calling up the other functions the program drops with a Segmentation Fault(core dumped) error. Everything works until then. I'll add the entire code in case the setup is wrong (possible as I don't particularly understand pointers or passing values and such)
#include <cmath>
#include <iostream>
using namespace std;
void discrim0(float a, float b, float c, float * root1, float * root2);
void discrimmore(float a, float b, float c, float * root1, float * root2);
void discrimless(float a, float b, float c, float * real, float * sqrtim);
int main()
{
float discrim;
float a;
float b;
float c;
float * root1=0;
float * root2=0;
float * real=0;
float * sqrtim=0;
char cAgain;
cout << "Welcome to the quadratic roots calculator." <<endl;
do
{
do
{
cout << "Please enter the three coefficient values of the" <<endl;
cout << "quadratic equation. The coefficient of x^2 must not"<<endl;
cout << "be 0." <<endl;
cin >> a >> b >> c;
if(a==0)
{
cout << "The value you entered for the coefficient of x^2"<<endl;
cout << "is not valid(0). Please enter a proper value."<<endl;
}
}while(a==0);
discrim=(b*b)-4*a*c;
if(discrim<0)
{
cout << "Your equation has two imaginary roots."<<endl;
//error occurs here
discrimless(a,b,c, real, sqrtim);
cout << *real << " + " << *sqrtim << "i" << endl;
cout << "and" << endl;
cout << *real << " - " << *sqrtim << "i" << endl;
}
if(discrim==0)
{
cout << "Your equation two roots of the same value."<<endl;
//error occurs here
discrim0(a,b,c, root1, root2);
cout << *root1 << " and " << *root2 << endl;
}
if(discrim>=0)
{
cout << "Your equation has two real roots, which are: "<<endl;
//error occurs here
discrimmore(a,b,c, root1, root2);
cout << *root1 << " and " << *root2;
}
cout << "Would you like to run another calculation? Y/y/N/n"<<endl;
cin >> cAgain;
}while(cAgain=='Y'||cAgain=='y');
return 0;
}
void discrim0(float a, float b, float c, float * root1, float * root2)
{
*root1= ((-b + sqrt((b*b)-4*a*c))/2*a);
*root2= ((-b - sqrt((b*b)-4*a*c))/2*a);
}
void discrimless(float a, float b, float c, float * real, float * sqrtim)
{
*real= (-b)/(2*a);
*sqrtim= (sqrt(-(b*b-4*a*c)))/(2*a);
}
void discrimmore(float a, float b, float c, float * root1, float * root2)
{
*root1= ((-b + sqrt((b*b)-4*a*c))/2*a);
*root2=((-b - sqrt((b*b)-4*a*c))/2*a);
}
I marked in the code where it happens. Essentially it will tell you the number of roots and then crash. I understand the general idea of seg fault that I am trying to access memory I don't have or something to that effect, but I don't really know why it is occurring. Also please keep in mind that I don't really understand technical speak too well. Thanks.
Aucun commentaire:
Enregistrer un commentaire