gpt4 book ai didi

c++ - 使用指针的二次方程问题

转载 作者:行者123 更新时间:2023-11-28 04:30:12 26 4
gpt4 key购买 nike

我成功地编写了一个程序,在给定三个系数的情况下找到标准形式二次方程的解。我现在正试图简化结果,以摆脱底部的“/2a”。因此就有了 simplify() 函数。

我已经开始创建简化函数,并尝试将解的虚部和实部除以 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);
}

最佳答案

您需要访问或更改指针指向的值,而不是指针本身:

void simplify(double* a, double* b, double* ans) //only run if complex
{
*ans /= (2 * *a);
*b /= (2 * *a);
}

编辑:或者,正如@Hans Passant 所说:

And consider that C++ allows you to declare its parameters as double& instead of double*. And go shopping for a decent IDE so you don't have to guess where the syntax error is located.

关于c++ - 使用指针的二次方程问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53142445/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com