慕桂英3389331
给出一个二次方程:x2−4.0000000x+3.9999999=0,10个有效数字的确切根是,r1=2.000316228和r2 = 1.999683772.使用float和double,我们可以编写一个测试程序:#include <stdio.h>#include <math.h>void dbl_solve(double a, double b, double c){
double d = b*b - 4.0*a*c;
double sd = sqrt(d);
double r1 = (-b + sd) / (2.0*a);
double r2 = (-b - sd) / (2.0*a);
printf("%.5f\t%.5f\n", r1, r2);}void flt_solve(float a, float b, float c){
float d = b*b - 4.0f*a*c;
float sd = sqrtf(d);
float r1 = (-b + sd) / (2.0f*a);
float r2 = (-b - sd) / (2.0f*a);
printf("%.5f\t%.5f\n", r1, r2);} int main(void){
float fa = 1.0f;
float fb = -4.0000000f;
float fc = 3.9999999f;
double da = 1.0;
double db = -4.0000000;
double dc = 3.9999999;
flt_solve(fa, fb, fc);
dbl_solve(da, db, dc);
return 0;}运行这个程序会给我:2.00000 2.000002.00032 1.99968请注意,这些数字并不大,但您仍然可以使用float.(事实上,上述方法并不是使用单精度或双精度浮点数求解二次方程的最佳方法,但即使使用更稳定的方法.)