You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++使用cout输出内容时如何添加合适填充空格实现列对齐

要实现对齐的格式化输出,你需要引入<iomanip>头文件,该头文件提供了控制输出格式的相关工具,具体修改方案如下:

实现步骤

  1. 在头文件区域新增引入#include <iomanip>
  2. 输出账单时,使用setw()设置每列的固定宽度,搭配left/right控制对齐方向
  3. 用fixed和setprecision(2)控制金额类浮点数保留2位小数,符合常规账单显示规范
  4. 原代码中存储小计的变量为int类型,会截断小数计算结果,建议改为float类型保证精度

修改后的完整代码

#include <iostream>
#include <iomanip>
using namespace std;

int main() {
    //variables
    string name;
    int fries = 0, burger = 0, donut = 0, ic = 0, sd = 0;
    const float friesp = 80, burgerp = 150, donutp = 30, icp = 25.50, sdp = 20;  
    float pricef = 0, priceb = 0, priced = 0, pricei = 0, prices = 0;
    float total = 0, vat = 0, bill = 0;
    
    //name of customer
    cout<<"Hi! Please type your name.";
    cin>>name;
    
    //amounts
    cout<<"Please enter the amount of fries ordered:";
    cin>>fries;
    pricef = fries*friesp;
    
    cout<<"Please enter the number of burger(s) ordered:";
    cin>>burger;
    priceb = burger*burgerp;
    
    cout<<"Please enter the number of donut(s) ordered:";
    cin>>donut;
    priced = donut*donutp;
    
    cout<<"Please enter the number of ice cream ordered:";
    cin>>ic;
    pricei = ic*icp;
    
    cout<<"Please enter the number of soft drink(s) ordered:";
    cin>>sd;
    prices = sd*sdp;
    
    //bill formula
    total = pricef+priceb+priced+pricei+prices;
    vat = total*0.20;
    bill = total + vat;
    
    //设置浮点数输出固定保留2位小数
    cout << fixed << setprecision(2);
    
    //prices
    cout<<"Hi "<<name<<"! Here is the summary of your order:"<<endl;
    // 第一列左对齐占10位,第二列左对齐占15位,第三列右对齐占10位,第四列右对齐占10位
    cout << left << setw(10) << fries << left << setw(15) << "fries" << right << setw(10) << friesp << right << setw(10) << pricef << endl;
    cout << left << setw(10) << burger << left << setw(15) << "burger(s)" << right << setw(10) << burgerp << right << setw(10) << priceb << endl;
    cout << left << setw(10) << donut << left << setw(15) << "donut(s)" << right << setw(10) << donutp << right << setw(10) << priced << endl;
    cout << left << setw(10) << ic << left << setw(15) << "ice cream" << right << setw(10) << icp << right << setw(10) << pricei << endl;
    cout << left << setw(10) << sd << left << setw(15) << "soft drink(s)" << right << setw(10) << sdp << right << setw(10) << prices << endl;
    
    //billing
    cout << left << setw(25) << "Subtotal:" << right << setw(20) << total << endl;
    cout << left << setw(25) << "20% VAT:" << right << setw(20) << vat << endl;
    cout << left << setw(25) << "Total bill:" << right << setw(20) << bill << endl;
    
    return 0; 
}

内容的提问来源于stack exchange,提问作者Samesassy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 03:45:05