首页 > 解决方案 > 如何只打印C中小数点后的整数

问题描述

这是我现在的输出

cost = 12.88;
printf("Cost: %.0lf dollars and %.2lf cents", cost, cost-floor(cost));

//输出

12 dollars and 0.88 cents

我需要我的输出看起来像这样

cost = 12.88
printf("%d Dollars and %d cents", cost)

输出

12 dollars and 88 cents

标签: c

解决方案


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

void print_cost(double cost)
{
    double int_part;
    double fract_part = modf(cost, &int_part);
    printf(
        "%d Dollars and %d cents", //"%d" based on your example
        (int) int_part, //we must therefore cast to integer
        abs((int)(fract_part * 100.0)) //fract is signed, abs value needed
    );
}

int main()
{
    print_cost(12.88);
    print_cost(-12.88);
    print_cost(12.8899);
    return 0;
}

参考:


推荐阅读