Я только начал изучать C++ с нуля на прошлой неделе, и по моему заданию мне нужно создать квадратичный алгоритм решения через несколько файлов: assign1.cpp, который содержит my main(), funcs.cpp, который содержит каждую функцию и make файл. У меня проблемы с этим.
Я должен получить коэффициенты от пользователя и вернуть их в структуру с тремя полями и использовать их введенную информацию в нескольких функциях для решения уравнения.
Мое программирование повсюду, и я получил большинство ошибок, чтобы уйти с коэф. в каждой функции и input.variable_name_here для a, b и c.
Кроме того, он хочет, чтобы мы использовали параметры.
Я почти не делаю этого с программой.
Вот что у меня есть:
//Program to solve quadratic equation
#include <iostream>
#include <cmath>
using namespace std;
//Structure for coefficients to be used
struct coeff {
double a;
double b;
double c;
};
//Prototypes?
double readCoeffs(), equSolver(), discr(), outResults();
//Read coefficients from user
double readCoeffs() {
coeff input;
cout << "Enter coefficient a: ";
cin >> input.a;
cout << "Enter coefficient b: ";
cin >> input.b;
cout << "Enter coefficient c: ";
cin >> input.c;
}
//Solve quadratic equation from user input
double equSolver() {
coeff input;
/*
need to somehow get the discrim variable from discr() to this function
discr();
*/
double solution1 = (pow(input.b, 2) + sqrt(discrim)) / (2 * input.a);
double solution2 = (pow(input.b, 2) - sqrt(discrim)) / (2 * input.a);
}
//Solves discriminent of quadratic equation
double discr() {
coeff input;
double discrim = pow(input.b, 2) - (4 * input.a * input.c);
}
/*
//Display on the screen results of the calculation
outResults() {
if (//root exists)
cout << "Quadratic equation with the following coefficients: \n";
cout << "a: " << value << "; b: " << value << "; c: " << value << "\n" << endl;
cout << "has the following roots ";
cout << "Root1: " << value << "; Root2: " << value << "\n" << endl;
else
cout << "Quadratic equation with the following coefficients: ";
cout << "a: " << value << "; b: " << value << "; c: " << value << "\n" << endl;
}
*/
readCoeffs()
объявляет input
объекта. Это означает, что вход существует только внутри функции, поэтому вы не можете использовать его в другом месте - он выходит из области действия, когда функция заканчивается. Кроме того, ваша функция объявляется с double
возвращаемым типом, но ничего не возвращает.
Подумайте о том, чтобы принять аргумент в качестве ссылки на структуру coeff
и объявить его void
?
void readCoeffs(coeff &input)
{
cout << "enter...";
cin >> input.a;
cin >> input.b;
cin >> input.c;
}
Затем сделайте то же самое для других функций (передавая структуру) и объявите свою структуру в своей функции main()
.
Изменение: добавлен пример функции с возвратом.
double discr(coeff &input)
{
double discrim = pow(input.b, 2) - (4 * input.a * input.c);
return discrim;
}
Я не мог удержаться, поэтому я переписал и реорганизовал код для решения проблемы. Это компилирует и делает то, что вы просите. Я также исправил квадратичную формулу, потому что это должно быть:
(-b + / - (b ^ 2 - 4ac))/2a
и вы
(b ^ 2 + / - (b ^ 2 - 4ac))/2a
#include <iostream>
#include <cmath>
using namespace std;
//Structure for coefficients to be used
struct coeff {
double a;
double b;
double c;
double sol1;
double sol2;
};
//Declarations
void readCoeffs(coeff &x);
void equSolver(coeff &x);
double discr(coeff x);
void outResults(coeff x);
//Read coefficients from user
void readCoeffs(coeff &input) {
cout << "Enter coefficient a: ";
cin >> input.a;
cout << "Enter coefficient b: ";
cin >> input.b;
cout << "Enter coefficient c: ";
cin >> input.c;
}
//Solve quadratic equation from user input
void equSolver(coeff &input) {
double solution1 = ((-1 * input.b) + sqrt(discr(input))) / (2 * input.a);
double solution2 = ((-1 * input.b) - sqrt(discr(input))) / (2 * input.a);
input.sol1 = solution1;
input.sol2 = solution2;
}
//Solves discriminent of quadratic equation
double discr(coeff input) {
double d;
d = pow(input.b, 2) - (4 * input.a * input.c);
return d;
}
void outResults(coeff input) {
if( std::isnan(input.sol1) || std::isnan(input.sol2)) {
cout << "Quadratic equation with the following coefficients could not be solved: \n";
cout << "a: " << input.a << "; b: " << input.b << "; c: " << input.c << "\n" << endl;
} else {
cout << "Quadratic equation with the following coefficients: \n";
cout << "a: " << input.a << "; b: " << input.b << "; c: " << input.c << "\n" << endl;
cout << "has the following roots ";
cout << "Root1: " << input.sol1 << "; Root2: " << input.sol2 << "\n" << endl;
}
}
int main() {
coeff Coeff;
readCoeffs(Coeff);
equSolver(Coeff);
outResults(Coeff);
}
descr
возвращает отрицательное число, так как equSolver
не знает комплексных чисел? (Хотя, возможно, именно этим isnan(...)
ваш isnan(...)
?)
discr
не возвращает значение, почему он не просто выбирает последнее вычисленное значение?» - вы можете помочь себе гораздо быстрее, чем кто-либо другой, с немного тренировок и усилий.