📜  C / C++中float和double的区别

📅  最后修改于: 2021-05-26 00:22:57             🧑  作者: Mango

为了表示浮点数,我们使用floatdoublelong double

有什么不同 ?

double的精度是float的2倍。

float是32位IEEE 754单精度浮点数1位符号,(8位为指数,23 *为值),即float具有7位十进制精度。

double是64位IEEE 754双精度浮点数(符号1位,指数11位,值52 *位),即double的精度为15位小数。

让我们举个例子(例子取自这里):
对于二次方程x2 – 4.0000000 x + 3.9999999 = 0 ,精确到10个有效数字的根是r1 = 2.000316228和r2 = 1.999683772

// C program to demonstrate 
// double and float precision values
  
#include 
#include 
  
// utility function which calculate roots of 
// quadratic equation using double values
void double_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);
}
  
// utility function which calculate roots of 
// quadratic equation using float values
void float_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);
}   
  
// driver program
int main(){
    float fa = 1.0f;
    float fb = -4.0000000f;
    float fc = 3.9999999f;
    double da = 1.0;
    double db = -4.0000000;
    double dc = 3.9999999;
  
    printf("roots of equation x2 - 4.0000000 x + 3.9999999 = 0 are : \n");
    printf("for float values: \n");
    float_solve(fa, fb, fc);
  
    printf("for double values: \n");
    double_solve(da, db, dc);
    return 0;
}  

输出:

roots of equation x2 - 4.0000000 x + 3.9999999 = 0 are : 
for float values: 
2.00000    2.00000
for double values: 
2.00032    1.99968
想要从精选的最佳视频中学习和练习问题,请查看《基础知识到高级C的C基础课程》。