C语言printf格式化打印--double类型变量保留两位小数

使用printf()格式化打印: 需要打印输出的变量类型为double,scanf()和printf()均使用占位符%lf:

#include <stdio.h>
#include <math.h>

int main() {
          
   
    double base;
    double height;
    double hypotenuse;
    scanf("%lf%lf", &base, &height);
    hypotenuse = sqrt(pow(base,2)+pow(height,2));
    printf("%lf
", hypotenuse + base + height);
    printf("%lf", base * height / 2);

    return 0;
}

输出的数据带了6位小数:

printf()输出结果保留2位小数

把printf()第一个参数的占位符%lf改成“%.2f”,则表示取第二个参数(double类型)的值输出,保留两位小数:

#include <stdio.h>
#include <math.h>

int main() {
          
   
    double base;
    double height;
    double hypotenuse;
    scanf("%lf%lf", &base, &height);
    hypotenuse = sqrt(pow(base,2)+pow(height,2));
    printf("%.2f
", hypotenuse + base + height);
    printf("%.2f", base * height / 2);

    return 0;
}

效果:

经验分享 程序员 微信小程序 职场和发展