我昨天刚刚开始学习C ++课程,而且我在学习语言方面遇到了一些困难。我正在尝试使用五个不同的用户给定系数(然后将它们放入数组中)来完成二次公式计算器,用于计算根,然后将较小的根(从五个方程式)放入一个新的数组中。
我没有得到的是如何使用现在放入数组中的系数来计算根,以及较小根的计算。到目前为止我的代码(我只修改主函数):
#include <iostream>
#include <cmath>
#include <cstdlib>
// True if candidate root is a root of the polynomial a*x*x + b*x + c = 0
bool check_root(int a, int b, int c, float root) {
// plug the value into the formula
float check = a * root * root + b * root + c;
// see if the absolute value is zero (within a small tolerance)
if (fabs(check) > 0.0001) {
std::cerr << "ERROR: " << root << " is not a root of this formula." << std::endl;
return false;
} else {
return true;
}
}
/* Use the quadratic formula to find the two real roots of polynomial. Returns
true if the roots are real, returns false if the roots are imaginary. If the roots
are real, they are returned through the reference parameters root_pos and root_neg. */
bool find_roots(int a, int b, int c, float &root_pos, float &root_neg) {
// compute the quantity under the radical of the quadratic formula
int radical = b*b - 4*a*c;
// if the radical is negative, the roots are imaginary
if (radical < 0) {
std::cerr << "ERROR: Imaginary roots" << std::endl;
return false;
}
float sqrt_radical = sqrt(radical);
// compute the two roots
root_pos = (-b + sqrt_radical) / float(2*a);
root_neg = (-b - sqrt_radical) / float(2*a);
return true;
}
int main() {
int b_array[5];
int c_array[5];
int smaller_root[5];
for (int i=0;i<5;i++){
std::cout << "Enter a 'b' coefficient for the quadratic function: a*x*x + b*x + c = 0" << std::endl;
int b;
std::cin >> b;
b_array[i] = b;
}
for (int i=0;i<5;i++){
std::cout << "Enter a 'c' coefficient for the quadratic function: a*x*x + b*x + c = 0" << std::endl;
int c;
std::cin >> c;
c_array[i] = c;
}
for (int i=0;i<5;i++){
float root_1, root_2;
bool success = find_roots(1,b_array[i],c_array[i], root_1,root_2);
if (root_1>root_2)
smaller_root[i] = root_1;
if (root_2>root_1)
smaller_root[i] = root_2;
} else {
std::cerr << "ERROR: Unable to verify one or both roots." << std::endl;
}
}
return 0;
}
谢谢!
答案 0 :(得分:1)
不应该这样:
if (root_1>root_2)
smaller_root[i] = root_1;
if (root_2>root_1)
smaller_root[i] = root_2;
} else {
std::cerr << "ERROR: Unable to verify one or both roots." << std::endl;
}
是
if (root_1>root_2) {
smaller_root[i] = root_1;
} else
if (root_2>root_1) {
smaller_root[i] = root_2;
} else {
std::cerr << "ERROR: Unable to verify one or both roots." << std::endl;
}
我认为在“其他”之前你所拥有的支撑。正在关闭for循环 }