使用割线根查找c ++的问题

时间:2011-05-11 00:55:20

标签: c++ methods

我正在努力为学校制定一个使用割线根寻找方法的计划。等式是:

  

(v / b)^ 2sin(alpha)= kr * Ts ^ 4 + Uc * Ts -q

我必须找到Ts。

不幸的是,我一直用作我的基础的例子对我不起作用:。它给出的根是-1.QNAN或类似的东西,所以我在某个地方的割线方法中有一个错误,我是C ++的新手,所以我在修复它时遇到了很多麻烦。任何帮助将不胜感激,如果有人可以告诉我代码,以便更容易发布代码,我将非常感激。谢谢 这是我目前的代码:

#include <iostream>
#include <cmath>
#include <fstream>
#include <iomanip>

using namespace std;

void secant (double, double, 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

int main ()
{
    double kr, uc, q, b, radians, Ts, x0, x1, root;
    int iteration; 
    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 (angle, radians, velocity, kr, uc, q, b, Ts, x0, x1, root, iteration);    
        }
    }
    system("pause");

    return 0;
}

void secant(double angle, double radians, double velocity, double kr, double uc, double q, double b, double Ts, double x0, double x1, double root, int iteration) 
{
    double xnminus1, xnplus1, xn;
    iteration=0; 
    xnminus1=x0;
    xn=x1;

    do
    {
        ++iteration;
        xnplus1 = xn - fx(kr, uc, Ts, q, velocity, radians, xn)*(xn-xnminus1)/
                  (fx(kr, uc, Ts, q, velocity, radians,xn)-fx(kr, uc, Ts, q, velocity, radians,xnminus1));

        cout<<"x"<<iteration+1<<" = "<<xnplus1<<endl;

        xnminus1 = xn;

        xn=xnplus1;

    }  

    while ((fabs(fx(kr, uc, Ts, q, velocity, radians, 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(kr, uc, Ts, q, velocity, radians, root) <<endl<<endl;    
}

double fx(double kr, double uc, double Ts, double q, double velocity, double b, double radians)
{
    return kr * pow(Ts, 4.0) + uc * Ts - q - pow(velocity/b, 2.0) * sin(radians);
}

1 个答案:

答案 0 :(得分:0)

你使用Ts而不定义它。有趣的是,它以蓝色突出显示......我认为有一位高级SO用户在某处轻笑自己......