我的项目是使用 setw()、setfill()、setiosflags() 创建这个输出:
Enter KWH used 993
C O M P S C I Electric
------------------------------------------------
Kilowatts Used 993
------------------------------------------------
Base Rate 993 @ $ 0.0475 $ 47.17
Surcharge $ 4.72
Citytax $ 1.42
______
Pay this amount $ 53.31
After May 20th Pay $ 55.44
我可以使用我的代码让它工作,但前提是使用的千瓦是 2 位数。如果它是更多的数字,我的右对齐不起作用。我可以编辑代码,使其正确地证明 3 位数、4 位数等。当我的代码将被测试时,我不知道将输入多少千瓦,所以我需要适用于任何数字长度的千瓦的代码。
/*
* File: main.cpp
* Author: -------------------------
*
* Created on ----------------------
*/
#include <cstdlib>
#include <iomanip>
#include <iostream>
using namespace std;
/*
*
*/
int main() {
float br; // base rate
float surcharge; // surcharge
float taxrate; // tax rate
float late; // late rate
float kwh; // kilowatts used
float bc; // base cost
float scc; // surcharge cost
float ctc; // city tax cost
br = .0475; // kilowatt rate
surcharge = .1; // surcharge rate
taxrate = .03; // tax rate
late = .04; //rate if payment is late
// cout.width(38);
cout << "Kilowatts used last month: ";
cin >> kwh; // get kwh used from user
cout << "\n";
cout << "\n";
cout << " C O M P S C I Electric " << "\n";
cout << setiosflags(ios::fixed|ios::showpoint) << setprecision(2); // set ios flags
cout << setfill('-') << setw(38) << "\n"; // display dashes in line
cout << setiosflags(ios::left) << "Kilowatts Used" << setfill(' ') << setw(23) << resetiosflags(ios::left) << kwh << "\n"; // output kwh formally
cout << setfill('-') << setw(38); // separate
cout << "\n" << "\n";
// calculations
bc = br * kwh;
scc = surcharge * kwh;
ctc = taxrate * kwh;
cout << left << "Base Rate " << kwh << " @ $0.0475 " << setfill(' ') << setw(4) << right << "$" << bc << "\n"; //output base rate, right justify cost
cout << left << "Surcharge" << setw(24) << right << "$" << scc << "\n"; // output surcharge cost, right justify cost
return 0;
}
我不明白setw()
当我使用resetiosflags(ios::left)
右对齐时的必要性。我尝试用setiosflags(ios::left)
andresetiosflags(ios::left)
替换right
and left
;
我是使用 netbeans c++ 编码和 g++ 编译的 c++ 初学者。我真的不太了解格式化控制台输出,所以我将不胜感激。我不一定必须使用顶部指定的 3 个函数,只要不同的方式与任何浮点长度一致即可。谢谢!