rootsimp.cpp

来自「从出版社求得的经典数值算法」· C++ 代码 · 共 78 行

CPP
78
字号
////////////////////////////////////////
//	程序5.2  简单迭代

//////////////////////////////////////////////////////////////////////////////////
//简单迭代
//
#include	<stdio.h>
#include        <stdlib.h>
#include	<conio.h>
#include	<math.h>

#define PRECISION	0.000001
#define MAX_Number	10000

#include "expressi.cpp"

void SimpleIterative(char FxString[])
{
	int k;
	float x0,x;

	if(CreateFx(FxString)) exit(0);

	printf("\n\nInput Initial Value:\nx0=");
	scanf("%f",&x);

	k=1;
	do{
		x0=x;
		x=f(x0);
		printf("\nx%d=%f",k,x);
		++k;
	}while(fabs(x-x0)>PRECISION&&k<MAX_Number);

	if(k>=MAX_Number)
		printf("\nSimple Iterative failed(k=%d)",k);
	else
	{
		printf("\n\nIterative times k=%d",k);
		printf("\nRoot x=%f",x);
	}
}

void main()
{
	char FxString[200];

	printf("\nInput function:  ");
	scanf("%s",FxString);
	SimpleIterative(FxString);
	printf("\n\n\007Press any key to quit!\n");
	getch();
}

/*
	运行实例

Input function: pow(x+1,1/3.)

Input Initial Value:
x0=0.0

x1=1.000000
x2=1.259921
x3=1.312294
x4=1.322354
x5=1.324269
x6=1.324633
x7=1.324702
x8=1.324715
x9=1.324717
x10=1.324718

Iterative times k=11
Root x=1.324718

Press any key to quit!
*/

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?