浮点值未显示准确数字的数字C

floating point values not displaying accurate number of digits c++

本文关键字:数字 显示      更新时间:2023-10-16

为我的$输出提供了正确的数字困难。

每次我插入例如语句中的8时,我都会获得3位数字的数字。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;

}

使用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

您必须编写std::cout.setf(std::ios::showpoint);,然后它将起作用。