c++程序简单问题,求助!

用c++编写二分法求解一元二次方程x^2-x-2=0在的根的程序。精确到0.00001。
#include
#include
double f(double x)
{
return x^2–x–2;
}
int main()
{
double a=0,b=3,c;
c=(b–a)/2;
while(f(c)!=0)
{
if(f(a)*f(b)>0)
b=c;
else
a=c;
}
cout<<setprecision(5)<<c;
return 0;
}
麻烦给我看一下,程序格式基本没什么问题,结果得不出来。

楼主可以改成这样,基本上保留了你原来的思路

 #include<iostream>
#include<iomanip>
using namespace std;
double f(double x)
{
    return x*x-x-2;
}
int main()
{
    double a=0,b=3,c;
    c=(b-a)/2;
    while(f(c) >= 0.00001 || f(c) <= -0.00001)
    {
        if(f(a)*f(c)<0)
        {
            b=c;
        }
        else
        {
            a=c;
        }
        c = (a + b) / 2;
    }
    cout<<setprecision(5)<<c<< endl;
    return 0;
}

改成下面那样能跑了
改了几个地方:
1.楼主的减号好像都是中文格式的-
2. x^2–x–2改成了x*x-x-2
3.while(f(c)!=0)改成了if(f(c)!=0),否则的话一旦f(c)!=0则一直在while循环中,无法跳出

#include<iostream>
#include<iomanip>
using namespace std;
double f(double x)
{
    return x*x-x-2;
}
int main()
{
    double a=0,b=3,c;
    c=(b-a)/2;
    if(f(c)!=0)
    {
        if(f(a)*f(b)>0)
            b=c;
        else
            a=c;
    }
    cout<<setprecision(5)<<c<< endl;
    return 0;
}

二分法一般会设置一个极小数来作为近似0的点,我这里使用MIN_ZERO,在精度允许的情况下可以避免死循环,
c=(b-a)/2 要改成 c=(b+a)/2,因为c每次是取a和b中间的一个值。
f(a)*f(b)>0要改成 result>0 ,只有这样才能判断c的值是取高了还是低了,从而来调整a和b的值
最后得到的答案是2

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

#define MIN_ZERO 1e-9
using namespace std;

double f(double x)
{
    return x*2-x-2 ;
}

int main()
{
    double a=0,b=3,c,result;
    c=(b+a)/2;
    while(result = f(c),abs(result) > MIN_ZERO)
    {
        if(result > 0)
            b = c;
        else
            a = c;
        c = (b+a)/2;
    }
    cout<<setprecision(5)<<c<<endl;
    return 0;
}