我正在尝试了解有关 C++ 编程的更多信息,但我在使用程序时遇到了困难。这个程序很简单,但我遇到了一个错误,我认为它可能与指针有关。我已经尝试多次修改代码,但我没有发现我所写的问题。任何有关如何解决问题的帮助或说明将不胜感激。
// The 'main' function for a program to test your function
// 'quadRoots'.
//===============================================================
#include <iostream>
int quadRoots(double a,double b, double c,double* r1,double* r2);
void printRoots(int nr,double* r1,double* r2);
using namespace std;
int main()
{
double root1[2], root2[2];
int nRoots;
// example with real roots
nRoots = quadRoots(1.0, 3.3, 2.1, root1, root2);
printRoots(nRoots,root1,root2);
// example with complex roots
nRoots = quadRoots(1.0, 3.3, 5.1, root1, root2);
printRoots(nRoots,root1,root2);
// example with real roots, one zero
nRoots = quadRoots(1.0, 3.3, 0.0, root1, root2);
printRoots(nRoots,root1,root2);
// example of a linear function that should produce 1 root
nRoots = quadRoots(0.7-1.0+0.3, 3.3, 2.1, root1, root2);
printRoots(nRoots,root1,root2);
// example that has no solutions
nRoots = quadRoots(0.7-1.0+0.3, 0.0, 5.5, root1, root2);
printRoots(nRoots,root1,root2);
cout << "Press Enter key to quit" << endl;
char qq = cin.get();
return(0);
}
void printRoots(int nr,double* r1,double* r2)
{
if(nr == 0){
cout << "No Roots" << endl << endl;
}
else if(nr == 1){
cout << "Root 1: " << r1[0] << endl << endl;
}
else if(fabs(r1[1]) < 0.0000001){ // print real roots
cout << "Root 1: " << r1[0] << endl;
cout << "Root 2: " << r2[0] << endl << endl;
}
else{ // print complex roots
if(fabs(r1[1]+r2[1]) > 0.00001){
cout << "Something is wrong: complex roots not in conjugate pairs." << endl;
}
else{
cout << "Root 1: " << r1[0] << " + " << fabs(r1[1]) << " i" << endl;
cout << "Root 2: " << r2[0] << " - " << fabs(r2[1]) << " i" << endl << endl;
}
}
}
int quadRoots(double a,double b,double c,double* r1,double* r2)
{
if ( a > 0 ){
if ( sqrt((b*b) - 4*a*c) > 0 ){
r1[0] = (-b + (sqrt((b*b) - 4*a*c))) / (2 *a);
r2[0] = (-b - (sqrt((b*b) - 4*a*c))) / (2 *a);
return (2);
}
else if (sqrt((b*b) - 4*a*c) == 0 ) {
r1[0] = (-b )/(2 *a);
return (1);
}
else if (sqrt((b*b) - 4*a*c) < 0 ) {
r1[1] = (-b + (-(sqrt(-(b*b) - 4*a*c)))) / (2 *a);
r2[1] = (-b - (-(sqrt(-(b*b) - 4*a*c)))) / (2 *a);
return (2);
}
}
else if (b == 0 ){
r1[0] = r2[0] = 0;
return (1);
}
else {
return (0);
}
}