请设计二分法算法,求方程:x立方-x-1=0在区间[1,1.5]内的解(精确度0.01) 10
2个回答
展开全部
//哥哥懒得切换到控制台下写
//就用win32写了个不伦不类的方法出来
//凭着记忆写的,,,说实话,,其他方法都忘记了,,就这二分法真的没忘记
//如同俺估计俺死的时候都不会忘记冒泡排序一样。。。。。
# include <Windows.h>
# include <math.h>
# pragma warning(disable:4996)
# include <wchar.h>
int __stdcall wWinMain( __in HINSTANCE , __in_opt HINSTANCE , __in_opt LPWSTR , __in int )
{
double x1 = 1, x2 = 1.5, err = 0.01, c = 0;
double y1 = x1 * x1 * x1 - x1 - 1;
double y2 = x2 * x2 * x2 - x2 - 1;
if(y1 * y2 > 0)
::MessageBox(0, L" Are you fucking kiding me? ", 0, 0); //给出的区间内无解
int timesLoop = (int) ceil((log(2.0 * err) / log(0.5) - 1.0));
for(int i = 0; i < timesLoop; ++i)
{
c = (x2 - x1) / 2; //二分法的增量
y1 = x1 * x1 * x1 - x1 - 1;
y2 = (x1 + c ) * (x1 + c ) * (x1 + c ) - (x1 + c ) - 1;
if(y2 * y1 < 0)
x2 = x1 + c;
else
x1 += c;
}
wchar_t dsp[56];
swprintf(dsp, L"Root is: %.2f", (x1 + x2) / 2);
::MessageBox(0, dsp, L"Root between [1, 1.5].....", MB_OK | MB_ICONINFORMATION);
return 0;
}
//就用win32写了个不伦不类的方法出来
//凭着记忆写的,,,说实话,,其他方法都忘记了,,就这二分法真的没忘记
//如同俺估计俺死的时候都不会忘记冒泡排序一样。。。。。
# include <Windows.h>
# include <math.h>
# pragma warning(disable:4996)
# include <wchar.h>
int __stdcall wWinMain( __in HINSTANCE , __in_opt HINSTANCE , __in_opt LPWSTR , __in int )
{
double x1 = 1, x2 = 1.5, err = 0.01, c = 0;
double y1 = x1 * x1 * x1 - x1 - 1;
double y2 = x2 * x2 * x2 - x2 - 1;
if(y1 * y2 > 0)
::MessageBox(0, L" Are you fucking kiding me? ", 0, 0); //给出的区间内无解
int timesLoop = (int) ceil((log(2.0 * err) / log(0.5) - 1.0));
for(int i = 0; i < timesLoop; ++i)
{
c = (x2 - x1) / 2; //二分法的增量
y1 = x1 * x1 * x1 - x1 - 1;
y2 = (x1 + c ) * (x1 + c ) * (x1 + c ) - (x1 + c ) - 1;
if(y2 * y1 < 0)
x2 = x1 + c;
else
x1 += c;
}
wchar_t dsp[56];
swprintf(dsp, L"Root is: %.2f", (x1 + x2) / 2);
::MessageBox(0, dsp, L"Root between [1, 1.5].....", MB_OK | MB_ICONINFORMATION);
return 0;
}
展开全部
#include <iostream>
#include <cmath>
using namespace std;
double f(double x)
{
return x*(x*x-1)-1;
}
int main()
{
double x0, x1=1, x2=1.5, f0, f1, f2, er = 0.01;
f1 = f(x1);
f2 = f(x2);
while ( x2 - x1 > er)
{
x0 = ( x1 + x2) / 2;
f0 = f(x0);
if( f0 * f1 < 0)
{
x2 = x0;
f2 = f0;
}
else
{
x1 = x0;
f1 = f0;
}
}
cout<<"root = "<<(x1+x2)/2<<endl;
return 0;
}
#include <cmath>
using namespace std;
double f(double x)
{
return x*(x*x-1)-1;
}
int main()
{
double x0, x1=1, x2=1.5, f0, f1, f2, er = 0.01;
f1 = f(x1);
f2 = f(x2);
while ( x2 - x1 > er)
{
x0 = ( x1 + x2) / 2;
f0 = f(x0);
if( f0 * f1 < 0)
{
x2 = x0;
f2 = f0;
}
else
{
x1 = x0;
f1 = f0;
}
}
cout<<"root = "<<(x1+x2)/2<<endl;
return 0;
}
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询