Вчера я только начал свой класс на C++, и у меня возникли некоторые трудности с приспособлением к языку. Я пытаюсь выполнить калькулятор квадратичной формулы, используя пять разных пользовательских коэффициентов (которые затем помещаются в массивы), которые используются для вычисления корней, а затем помещают меньшие корни (из пяти уравнений) в новый массив.C++ для путаницы и массива Confusion
Что я не получаю, так это то, как использовать коэффициенты, которые теперь помещаются в массивы, для вычисления корней, а также вычисления для меньшего корня. Мой код до сих пор (я только изменяю основную функцию):
#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;
}
Спасибо!
Вы знаете, где именно все начинает идти не так? Это только в третьем для цикла, что вы не знаете, как использовать коэффициенты? Или вы думаете, что проблема начинается где-то в другом месте? – PunDefeated
Ваш второй 'if' должен быть' else if'. В противном случае вы будете сообщать об ошибке, когда 'root_1' является меньшим корнем. – Barmar
Я не вижу никаких проблем с тем, как вы используете массивы. В чем именно проблема, с которой вы сталкиваетесь? Покажите свой образец ввода, ожидаемые результаты и результаты, которые вы получаете. – Barmar