Мне нужно создать программу деления пополам для квадратичных уравнений. Вот инструкции для двух отдельных этапов:Как вы пишете прототип функции в C++, который возвращает структуру?
Программа должна удовлетворять следующим требованиям:
коэффициенты а, Ь, с квадратного уравнения должны быть считаны с клавиатуры с помощью отдельной функции назван
readCoeffs()
. Функция должна возвращать вызывающей стороне структуру со всеми тремя коэффициентами, считанными. t может быть 3 поля структуры или одно поле с 3-элементным массивом.Функция, которая вычисляет корни, возвращает результаты вызывающей стороне в виде структуры с тремя полями: root1, root2 и существует (логическая переменная, чтобы определить, существуют ли корни).
Я не могу правильно написать прототипы функций и заголовки функций. Когда я пишу их следующим образом:
struct calcRoots(double, double, double, double quadfunc(double), bool&);
struct readCoeffs();
int main(){
Я получаю ошибки. Я думаю, что Microsoft Visual Studio ожидает, что я создам структуры с фигурными скобками и точкой с запятой. Я очень потерян. Любая обратная связь очень ценится.
Вот код, с которым я работаю. Я постоянно его модифицирую. Это мой первый курс на C++. Я борюсь.
/****************************************************************************
//File: bisect.cpp
//Finds the root of a function using the bisection method
#include <iostream>
#include <cmath>
#include <fstream>
using namespace std;
struct coeffStru{
double a;
double b;
double c;};
struct rootStru{
double root1;
double root2;
bool exists;
};
//function prototypes
struct calcRoots(double, double, double, double f(double),bool&);
double quadfunc(struct, double);
struct readcoeffs(coeffStru);
int main() {
double xLeft=-10.0;
double xRight=10.0; //end points of interval
double epsilon; //exists tolerance
double root; //root found by bisect
bool exists; //exists flag
//Get tolerance
cout<< "Enter tolerance: ";
cin>>epsilon;
struct coeffStru = readcoeffs();
//use bisect calcRoots function to look for root of function f
struct rootStru = calcRoots(xLeft, xRight, epsilon, quadfunc, exists);
//display result
if (!exists){
cout<< "Root found at "<<root
<<" \nValue of f(x) at root is: "<<f(root);
system("PAUSE");
return 0;
}
else{
cout<<"There may be no root in ["<<xLeft<<", "<<xRight<<"]"<<endl;
system("PAUSE");
return 0;
}
}
//Struct return type readcoeffs function
struct readcoeffs(coeffStru){
cout<<"Enter values for a,b,and c of a quadratic equation."<<endl;
cin>>a>>b>>c;
return struct coeffStru;
}
//Implements bisection method to find a root of function f
//in interval [xLeft, xRight].
//PRE: xLeft, xRight, and epsilon are defined.
//POST: Returns midpoint of xLeft and xRight if the difference between thses values is <= epsilon. Returns true to exists if there is no root.
struct calcRoots (double xLeft, double xRight, double epsilon, struct coeffStru, double quadfunc(double), bool& exists) //IN: endpoints of interval for possible root, IN: exists tolerance, IN: the function, OUT: exists flag
{
double xMid; //midpoint of interval
double fLeft;
double fRight; //function values at xLeft, xRight,
double fMid; //and xMid
//Compute function values at initial endpoints of interval
fLeft = quadfunc(xLeft,coeffStru);
fRight = quadfunc(coeffStru, xRight);
//Repeat while interval > exists tolerance
while (fabs (xLeft - xRight) > epsilon)
{
//Compute function value at midpoint
xMid = (xLeft + xRight)/ 2.0;
fMid = quadfunc(coeffStru, xMid);
//Test function value and reset interval if root not found
if(fMid ==0.0) //if xMid is the root
root1 = xMid; //set root1 to xMid
else{
xRight = xMid;
xMid = (xLeft + xRight)/ 2.0;
fMid = f(coeffStru, xMid);
}
if(fLeft * fMid < 0.0) //root in [xLeft, xMid]
//Display next interval
cout<< "New interval is [" <<xLeft
<< ", " <<xRight << "]"<<endl;
} //ends 1st while loop
//If no change of sign in the interval, there is no unique root
exists = (fLeft * fRight) >0; //test for same sign - set exists
if(exists){
return -999.0; //no 1st root - return to caller
}
//Return midpoint of last interval
root1 = (xLeft + xRight)/2.0;
//Compute function values at initial endpoints of interval
fLeft = f(coeffStru, xLeft);
fRight = f(coeffStru, xRight);
//Repeat while interval > exists tolerance
while (fabs (xLeft - xRight) > epsilon)
{
//Compute function value at midpoint
xMid = (xLeft + xRight)/ 2.0;
fMid = f(coeffStru, xMid);
//Test function value and reset interval i root not found
if(fMid ==0.0) //xMid is the root
return xMid; //return the root
else if (fLeft * fMid < 0.0) //root in [xLeft, xMid]
xRight = xMid;
else //root in [xMid, xRight]
xLeft = xMid;
//Display next interval
cout<< "New interval is [" <<xLeft
<< ", " <<xRight << "]"<<endl;
} //ends 2nd while loop
//If no change of sign in the interval, there is no unique root
exists = (fLeft * fRight) > 0; //test for same sign - set exists
if(exists){
return -999.0; //no 2nd root - return to caller
}
//Return midpoint of last interval
root2 = (xLeft + xRight)/2.0;
return struct rootStru;
} //ends calcRoots method
//Function whose root is being found.
//PRE: x is defined.
//POST: Returns f (x)
double quadfunc(struct coeffStru, double x){
return a * pow(x, 2.0) - b* pow(x, 1.0) + c;}
************************************************************/
Я получаю много ошибок, как вы можете себе представить. Теперь моя главная проблема заключается в передаче переменных и структур по ссылке и значениям.
Присылайте код и сообщение об ошибке, пожалуйста! – Mahesh
Да, компилятор ожидает, что вы узнаете какой-то синтаксис. [Возможно, возьмите хорошую книгу] (http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) – AJG85
Похоже, вы прыгаете в пул и не делаете умеют плавать. Сначала начните изучение синтаксиса! –