我为寻找方程式的根源而编写的程序已接近完成,但我遇到了一个小问题。我用来将速度和角度的变化值分配给方程式的嵌套循环不起作用。无论是在循环中还是在调用fx割线的某个地方,我都会错过一个错误。它不断给我相同的数字,根数,迭代次数和f(x)。如果有人能帮我找到我的错误,我会非常感激:)
#include<iostream>
#include<cmath>
#include<iomanip>
#include<fstream>
using namespace std;
// Declaration of functions used
void secant(double, double, double, double, double, double, double, double, double&, int& );
double fx( double, double, double, double, double, double, double);
const double tol=0.0001;
// Tolerance for convergence
const int max_iter=50; // Maximum iterations allowed
// main program
int main()
{
int iteration; // Number of iterations
double kr, uc, q, b, radians;
double x0, x1; // Starting values for x
double root; // Root found by secant method
const double PI = 4.0*atan(1.0);
ifstream datain ("shuttle.txt");
ofstream dataout ("results.txt");
datain >> kr >> uc >> q >> b;
int velocity = 16000;
double angle =10;
x0= 1000;
x1 = 200;
for (int velocity = 16000; velocity <= 17500; velocity += 500)
{
for (int angle = 10; angle <= 70; angle += 15)
{
radians= angle * PI/180 ;
cout << velocity << endl;
cout << radians << endl;
cout << angle << endl;
secant (radians, velocity, kr, uc, q, b, x0, x1, root, iteration);
}
}
system("pause");
}
// Definition of function "secant"
// Receives a, b, c, d and x0 values from main program
// Returns root and the iterations required
void secant(double radians,double velocity, double kr, double uc, double q, double b, double x0, double x1, double& root, int& iteration)
{
double xnminus1, xnplus1, xn; // Local variables
iteration=0; // Initialize iterations
xnminus1=x0;
xn=x1;
do
{
++iteration;
xnplus1 = xn - fx(radians, velocity, kr, uc, q, b, xn)*(xn-xnminus1)/(fx(radians, velocity, kr, uc, q, b, xn)-fx(radians, velocity, kr, uc, q, b, xnminus1));
cout<<"x"<<iteration+1<<" = "<<xnplus1<<endl;
xnminus1 = xn;
xn=xnplus1;
} while ((fabs(fx(radians, velocity, kr, uc, q, b, xnplus1)) >= tol )&& (iteration < max_iter));
root=xnplus1;
cout<<"\nThe root is = "<<root<<endl;
cout<<"The number of iterations was = "<<iteration<<endl;
cout<<"The value of f(x) at the root = "<<fx(radians, velocity, kr, uc, q, b, root)<<endl<<endl;
}
// Defines "fx"
double fx(double radians,double velocity, double kr, double uc, double q, double b, double ts)
{
return kr * pow(ts,4.0) + uc * ts - q - pow(velocity / b, 2.0) * sin(radians);
}
答案 0 :(得分:0)
您有多个已定义的变量,请尝试删除main中最外层的速度和角度:
int velocity = 16000; // remove this one
double angle =10; // and this one
x0= 1000;
x1 = 200;
for (int velocity = 16000; velocity <= 17500; velocity += 500)
{
for (int angle = 10; angle <= 70; angle += 15)
{