试图格式化我的printf以对齐美元符号和美分

时间:2019-02-13 05:03:58

标签: c printf

想要使结果看起来像这样:

# of people Served:       8
Bill Amount:       $ 399.60
Surcharge Amount:   $ 80.00
Final Bill Amount: $ 479.60

这里没有很好的显示,我的意思是排列在零处

#include <stdio.h>
#include <conio.h>

 int main()
{
    int numberPeople;
    float surchargeAmount, totalBill, finalBill;

    printf("please enter number of people: ");
    scanf(" %d", &numberPeople);
    if (numberPeople <= 5.0)
    {
        surchargeAmount = 0;
    }
    else if (numberPeople <= 10.0)
    {
        surchargeAmount = 80.0;
    }
    else if (numberPeople <= 20.0)
    {
        surchargeAmount = 150.0;
    }
    else if (numberPeople > 20.0)
    {
        surchargeAmount = 200.0;
    }
    totalBill = numberPeople * 49.95;
    finalBill = (numberPeople * 49.95) + surchargeAmount;
    printf("# of people served:%d \n"
        "Bill Amount:%.2f \n"
        "Surcharge Amount:%.2f \n"
        "Final Bill Amount:%.2f \n", numberPeople, totalBill, 
surchargeAmount, finalBill);
    getch();
    return 0;

2 个答案:

答案 0 :(得分:2)

您需要在printf格式说明符中使用适当的field width对齐输出消息。

例如:

printf( "# of people served: %d \n"
        "Bill Amount:        %8.2f \n"
        "Surcharge Amount:   %8.2f \n"
        "Final Bill Amount:  %8.2f \n",
        numberPeople, totalBill, 
        surchargeAmount, finalBill);

输出:

# of people served: 3 
Bill Amount:          149.85 
Surcharge Amount:       0.00 
Final Bill Amount:    149.85 

这是一个实时示例:https://ideone.com/Iko1BY

答案 1 :(得分:0)

尝试这种方式:

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

#define CURRENCY "$"

struct Bill {
    char* item;
    double amount;
};

enum {
    BUF_SIZE = 16
};

int main(void)
{
    char buf[BUF_SIZE];
    struct Bill bill[] = {
        {"First:", 123.45},
        {"Second:", 0.50},
        {"Third:", 123456.78}
    };

    for (size_t i = 0; i < sizeof(bill) / sizeof(struct Bill); i++) {
        snprintf(buf, sizeof(buf), CURRENCY " %.2f", bill[i].amount);
        printf("%-10s %16s\n", bill[i].item, buf);
    }

    return EXIT_SUCCESS;
}

因此您可以获得:

First:             $ 123.45
Second:              $ 0.50
Third:          $ 123456.78