我在使用割线方法
运行c ++代码以查找自定义方程的根时遇到问题我在声明变量方面遇到了问题。它显示错误
错误:' p'在这方面没有申明 if(f(x1,c,p,pr)* f(x2,c,p,pr)< 0){ ^ 和
错误:' pr'在这方面没有申明 ^
#include <iostream>
using namespace std;
#include <iostream>
// C++ Program to find root of an
// equations using secant method
#include <bits/stdc++.h>
using namespace std;
// function takes value of x and returns f(x)
float f(float x, float c, float p, float pr)
{
float f = pow((c/2)/(1 + x/2),p) + pow((c/2)/(1 + x/2),(p-1)) + pow(100/(1 + x/2),p) - pr;
return f;
}
void secant(float x1, float x2, float E)
{
float n = 0, xm, x0, c;
if (f(x1,c,p,pr) * f(x2,c,p,pr) < 0) {
do {
// calculate the intermediate value
x0 = (x1 * f(x2,c,p,pr) - x2 * f(x1,c,p,pr)) / (f(x2,c,p,pr) - f(x1,c,p,pr));
// check if x0 is root of equation or not
c = f(x1,c,p,pr) * f(x0,c,p,pr);
// update the value of interval
x1 = x2;
x2 = x0;
// update number of iteration
n++;
// if x0 is the root of equation then break the loop
if (c == 0)
break;
xm = (x1 * f(x2,c,p,pr) - x2 * f(x1,c,p,pr)) / (f(x2,c,p,pr) - f(x1,c,p,pr));
} while (fabs(xm - x0) >= E); // repeat the loop
// until the convergence
cout << "Root of the given equation=" << x0 << endl;
cout << "No. of iterations = " << n << endl;
} else
cout << "Can not find a root in the given inteval";
}
// Driver code
int main()
{
float c ;
float p ;
float pr ;
cout << "Please enter the coupon" << endl ;
cin >> c ;
cout << "Please enter the period" << endl ;
cin >> p ;
cout << "Please enter the dirty price" <<endl ;
cin >> pr;
float x1 = 0, x2 = 15, E = 0.0001;
// initializing the values
secant(x1, x2, E);
return 0;
}
答案 0 :(得分:0)
您可以将变量传递给函数,将这些参数添加到函数
void secant(float x1, float x2, float E,float c,flaot p,float pr)
并像这样调用函数
secant(x1, x2, E,c,p,pr);