【发布时间】:2016-05-05 04:31:17
【问题描述】:
我昨天刚开始我的 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;
}
谢谢!
【问题讨论】:
-
你知道事情到底是从哪里开始出错的吗?是否只有在第三个 for 循环中您不知道如何使用系数?还是您认为问题是从其他地方开始的?
-
您的第二个
if应该是else if。否则,只要root_1是较小的根,就会报错。 -
我认为您使用数组的方式没有任何问题。您遇到的具体问题是什么?显示您的示例输入、预期结果以及您得到的结果。
-
我不明白最后的错误信息。看起来只要两个根相同,它就会报告错误,每当
b^2 = 4ac时就会发生这种情况。为什么这意味着它无法验证根? -
这段代码你真的编译成功了吗?
标签: c++ arrays loops for-loop main