我成功地编写了一个程序,以给定三个系数找到标准形式二次方程的解。我现在正在尝试简化结果,以消除底部的“ / 2a”。因此是simple()函数。
我已经开始创建简化函数,并试图将解的虚部和实部除以2a。不知何故,它给出了错误:
"error:invalid operands of types 'int' and 'double *' to binary 'operator*'" on lines 105 and 106.
我怀疑这与我作为参数传递的指针和引用有关。我是这个主意。
此外,仅一句,我从未真正看到过使用“ / =”。是允许的吗?我知道“ + =”可以。
#include <iostream>
#include <string>
#include <cmath>
#include <cstdlib> //simplify the answer
using namespace std;
int count = 0;
//prototyping
double ans_1(double, double, double);
double ans_2(double, double, double);
double nanhe(double, double, double);
void simplify(double*, double*, double*);
int main()
{
double a, b, c;
cout << "Quadratic Equation Solver \n";
cout << "Enter a value for a: ";
cin >> a;
cout << endl;
cout << "Enter a value for b: ";
cin >> b;
cout << endl;
cout << "Enter a value for c: ";
cin >> c;
cout << endl;
if (isnan(sqrt((b * b) - (4 * a * c)))) {
count++;
}
if (!count) {
double answer01 = ans_1(a, b, c);
double answer02 = ans_2(a, b, c);
cout << "X=" << answer01 << endl;
cout << "X=" << answer02 << endl;
}
else if (count) //could route these imag ones to separate funcitons instead of count++
{
double answer01 = ans_1(a, b, c);
double answer02 = ans_1(a, b, c);
cout << "X=(" << -b << "+" << answer01 << "i)/" << 2 * a << endl;
cout << "X=(" << -b << '-' << answer02 << "i)/" << 2 * a << endl;
}
system("pause");
}
double ans_1(double a, double b, double c)
{
double ans1;
double temp_c = sqrt((b * b) - (4 * a * c));
if (isnan(temp_c)) {
temp_c = nanhe(a, b, c);
}
if (!count) {
ans1 = ((-b + temp_c) / (2 * a));
}
else if (count) {
ans1 = ((temp_c));
}
simplify(&a, &b, &ans1);
return ans1;
}
double ans_2(double a, double b, double c)
{
double ans2;
double temp_d = sqrt((b * b) - (4 * a * c));
if (isnan(temp_d)) {
temp_d = nanhe(a, b, c);
}
if (!count) {
ans2 = ((-b - temp_d) / (2 * a));
}
else if (count) {
ans2 = (temp_d);
}
simplify(&a, &b, &ans2); //line under this should alter ans2 so its returning the simplified version instead, or just make a new variable instead of ans2
return ans2;
}
double nanhe(double a, double b, double c) //still need to apply simplify() to nanhe
{
double temp_help;
temp_help = sqrt(-1 * ((b * b) - (4 * a * c)));
count++;
return temp_help;
}
void simplify(double* a, double* b, double* ans) //only run if complex
{
ans /= (2 * a);
b /= (2 * a);
}
答案 0 :(得分:1)
您需要访问或更改指针指向的值,而不是指针本身:
void simplify(double* a, double* b, double* ans) //only run if complex
{
*ans /= (2 * *a);
*b /= (2 * *a);
}
编辑: 或者,如@Hans Passant所说:
并考虑到C ++允许您将其参数声明为double& 而不是double *。并去购买像样的IDE,这样您就不必 猜测语法错误的位置。