求一个关于计算方法中二分法的C语言程序
可以使用宏定义定义F(X),输入二分法的区间及精确度,可求的F(X)的解。
我上计算方法时自己写的二分法程序
大部分都是格式控制,真正计算的部分并不多。程序在Turbo C 3.0 和 VC 6.0 下调试通过。#include <stdio.h>
#include <math.h>
#include <conio.h>
main()
{
double a, b, c, d;
double xx, x1, x2;
double fxn1, fxnx;
double f(double, double, double, double, double);
int i, n;
FILE *fp;
fp = fopen("output.txt", "w");
//clrscr(); //清屏,可以注释掉
printf("\nax^3 + bx^2 + cx + d = 0.\n");
printf("Please input a b c d (e.g. 1 4 0 -10): ");
scanf("%lf %lf %lf %lf", &a, &b, &c, &d);
printf("Please input [ x1 , x2 ] (e.g. 1 2): ");
scanf("%lf %lf", &x1, &x2);
printf("Please input n (e.g. 8): ");
scanf("%d", &n);
fprintf(fp, "\nax^3 + bx^2 + cx + d = 0.\n");
fprintf(fp, "a = %.10lf, b = %.10lf, c = %.10lf, d = %.10lf.\n ", a, b, c, d);
fprintf(fp, "[ x1 , x2 ] = [ %.10lf , %.10lf ].\n", x1, x2);
fprintf(fp, "n = %d.\n", n);
fprintf(fp, "\n n\t[ x1 , x2 ]\t\txn\n", i, x1, x2, xx);
fprintf(fp, "-------------------------------------------------------------\n");
for (i = 1; i <= n; i++)
{
fxn1 = f(a, b, c, d, x1);
xx = (x1 + x2) / 2;
fxnx = f(a, b, c, d, xx);
fprintf(fp, "%2d\t[ %.10lf , %.10lf ]\t\t%.10f\n", i, x1, x2, xx);
if (fxnx == 0) goto p;
if (fxn1 * fxnx > 0)
x1 = xx;
else
x2 = xx;
}
p:
fprintf(fp, "-------------------------------------------------------------\n");
fprintf(fp, "The solution is : a* = %.2lf.\n", xx);
fclose(fp);
printf("The solution has been saved in file OUTPUT.TXT.\n");
getch();
return;
}
double f(a, b, c, d, x)
double a, b, c, d, x;
{
double temp;
temp = a * pow(x, 3) + b * pow(x, 2) + c * x + d;
return temp;
}
算例结果:
ax^3 + bx^2 + cx + d = 0.
a = 1.0000000000, b = -6.9000000000, c = 15.8700000000, d = -12.1670000000.
[ x1 , x2 ] = [ 1.5000000000 , 2.5000000000 ].
n = 8.
n [ x1 , x2 ] xn
-------------------------------------------------------------
1 [ 1.5000000000 , 2.5000000000 ] 2.0000000000
2 [ 2.0000000000 , 2.5000000000 ] 2.2500000000
3 [ 2.2500000000 , 2.5000000000 ] 2.3750000000
4 [ 2.2500000000 , 2.3750000000 ] 2.3125000000
5 [ 2.2500000000 , 2.3125000000 ] 2.2812500000
6 [ 2.2812500000 , 2.3125000000 ] 2.2968750000
7 [ 2.2968750000 , 2.3125000000 ] 2.3046875000
8 [ 2.2968750000 , 2.3046875000 ] 2.3007812500
-------------------------------------------------------------
The solution is : a* = 2.30.
不好意思,程序没有注释哦,不过不难,肯定能看懂的。~呵呵~~
[[it] 本帖最后由 grape16 于 2008-9-19 23:06 编辑 [/it]]