无法为我的$输出提供正确的数字。
每当我在声明中插入例如8时,我会得到3位数的Ex。 10.9 虽然我希望它显示10.90美元
我刚刚添加了setprecision,希望它能解决问题,不起作用
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int Ts; // holds Ts
float Price, Tcost, Total;
cout << "How many shirts you like ?" << endl;
cin >> Ts;
Total = 12 * Ts;
if ( 5 < Ts && Ts < 10)
Tcost = (Total - (.10 * Total));
Price = (Tcost / Ts);
cout << "he cost per shirt is $" << setprecision(4) << Price << " and the total cost is $" << Tcost << setprecision(4) << endl;
return 0;
}
答案 0 :(得分:2)
使用std::fixed
的组合(其将设置由setprecision(N)
决定的打印点之后的小数位数)和std::setprecision(2)
(因此打印两位小数),并且代码现在应该可以工作:
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int Ts; // holds Ts
float Price, Tcost, Total;
cout << "How many shirts you like ?" << endl;
cin >> Ts;
Total = 12 * Ts;
if ( 5 < Ts && Ts < 10)
Tcost = (Total - (.10 * Total));
Price = (Tcost / Ts); // The indentation is weird here
// but I will leave it as it is
cout << "he cost per shirt is $" << fixed << setprecision(2) << Price << " and the total cost is $" << Tcost << setprecision(2) << endl;
return 0;
}
我得到的输出是:
How many shirts you like ?
8
he cost per shirt is $10.80 and the total cost is $86.40
答案 1 :(得分:0)
你必须写std::cout.setf(std::ios::showpoint);
然后才能运作。