二分法输入方程,c++

Input equation in bisection method, C++

本文关键字:输入 方程 c++ 二分      更新时间:2023-10-16

我有这样的代码:

#include <iostream>
#include <cmath>
#include <stdlib.h>
using namespace std;
double f(double x);
double biseccion(double a, double b, double tolerancia, int maxiter);
int main()
{
    double a, b, raiz;
    double tolerancia=0.00000;
    int maxiter=25;
    cout << "Input begin of interval: ";
    cin >> a;
    cout << "Input end of interval: ";
    cin >> b;
    cout << "n";
    cout << "  # de"<<"n"<<"Iteration"<<"t"<<"   A"<<"t"<<"   B"<<"t"<<"   C"<<"t"<<"   f(c)"<<endl;
    raiz=biseccion(a,b,tolerancia,maxiter);
    cout << "n";
    cout << "The root is: "<< raiz <<endl;
    return 0;
}
 double f(double x)
 {
        return x*x*x-x-2;
 }
 double biseccion(double a, double b, double tolerancia, int maxiter)
 {
        double c;
        int numiter=1;
        do
        {
            c=(a+b)/2;
            if(f(a)*f(c)<0)
            {
               b=c;
            }
            else
            {
               a=c;
            }
            cout<<"     "<<numiter<<"t"<<"t"<<a<<"t"<<b<<"t"<<c<<"t"<<f(c)<<endl;
            numiter++;
         }
         while((abs(f(c))>tolerancia)&&(numiter<maxiter));
         return c;
}

在我的代码中不是写"x*x*x-x-2",我希望用户在要求开始间隔之前输入它。我该怎么做呢?

我尝试使用一个变量来存储"x*x*x-x-2",但没有工作。

您需要解析输入,这可能不像您想象的那么容易,但是有一些库可以帮助您。

muparser.sourceforge.net/

code.google.com/p/expressionparser/

partow.net/programming/exprtk/index.html

也是c#中的一个解决方案,可能也会对您有所帮助。

在。net中有字符串数学计算器吗?