我有一个简单的程序,要求提供电影的名称,以及为set1和set2出售的门票数量。然后它用这些值进行一些计算并显示结果。我唯一的问题是我似乎无法按照我希望的方式排列小数值。
控制台中的最后三行输出应始终如下(美元符号和小数点排成一行):image。但是当我为set1的票据输入1,为set2的票据输入0时,反之亦然,它看起来像这样:image。关于如何使输出ALWAYS排在第一个屏幕截图中的任何想法?提前谢谢。
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
int main() {
string film = "";
int set1 = 0;
int set2 = 0;
// the cinema always takes this 20% cut.
const double CINEMA_FEE = 0.20;
double profit = 0;
double profitMinusFee = 0;
double paidToMovieMaker = 0;
cout << "What is the name of the film: ";
getline(cin, film);
cout << "How many tickets for set1 sold: ";
cin >> set1;
cout << "How many tickets for set2 sold: ";
cin >> set2;
cout << "Film Name:" << setw(20) << "\"" << film << "\"" << endl;
cout << "Set1 tickets sold:" << setw(16) << set1 << endl;
cout << "Set2 tickets sold:" << setw(16) << set2 << endl;
set1 *= 10;
set2 *= 6;
profit = set1 + set2;
profitMinusFee = profit * CINEMA_FEE;
paidToMovieMaker = profit - profitMinusFee;
// needs to always show two decimal points and fixed
cout << setprecision(2) << fixed;
cout << "The total monetary profit:" << setw(5) << "$ " << profit << endl;
cout << "The net monetary profit:" << setw(7) << "$ " << profitMinusFee << endl;
cout << "Total paid to movie maker:" << setw(5) << "$ " << paidToMovieMaker << endl;
return 0;
}
答案 0 :(得分:0)
我认为你的问题是你在美元符号上设置宽度而不是数字。
这似乎为我解决了这个问题:
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
int main() {
string film = "";
int set1 = 0;
int set2 = 0;
// the cinema always takes this 20% cut.
const double CINEMA_FEE = 0.20;
double profit = 0;
double profitMinusFee = 0;
double paidToMovieMaker = 0;
cout << "What is the name of the film: ";
getline(cin, film);
cout << "How many tickets for set1 sold: ";
cin >> set1;
cout << "How many tickets for set2 sold: ";
cin >> set2;
cout << "Film Name:" << setw(20) << "\"" << film << "\"" << endl;
cout << "Set1 tickets sold:" << setw(16) << set1 << endl;
cout << "Set2 tickets sold:" << setw(16) << set2 << endl;
set1 *= 10;
set2 *= 6;
profit = set1 + set2;
profitMinusFee = profit * CINEMA_FEE;
paidToMovieMaker = profit - profitMinusFee;
// needs to always show two decimal points and fixed
cout << setprecision(2) << fixed;
cout << "The total monetary profit: $ " << setw(10) << profit << endl;
cout << "The net monetary profit : $ " << setw(10) << profitMinusFee << endl;
cout << "Total paid to movie maker: $ " << setw(10) << paidToMovieMaker << endl;
return 0;
}
请记住setw()
会影响之后的内容。