我无法在C ++中使用设置精度

时间:2018-02-07 21:32:17

标签: c++

我无法在C ++中使用设置精度。我一直得到3位小数而不是1位。如果我输出7位和32位,则输出为21.875。我需要它以21.9出现。我是相当新的,我可以使用任何帮助!感谢

#include <iostream>
#include <iomanip>

using  namespace std;

int main()
{
    int scored, attmp;

    cout<<"Enter the number of goals that were scored: ";
    cin>> scored;                                                   

    if( scored < 0 )
    {
        cout<<"Error: The number of goals must be greater than 0. Try Again: 
        ";
        cin>> scored; 
    }

    if( scored > 0 )
    {

    }
    cout<<"\nEnter the number of shots that were attempted: ";
    cin>>attmp;                                                     

    if( attmp < 0 )
    {
        cout<<"Error: The number of goal must be greater that 0. Try again: 
        ";
        cin>> attmp;
    }

    if( attmp >0 )
    {

    }

    double shootp= ((double)scored) / (attmp) * 100.0;      

    cout<<"\nThe Shooting Percentage is "<< shootp << setprecision(1) << 
endl;   
return 0;       
}

2 个答案:

答案 0 :(得分:4)

在输出浮点变量之前,您需要同时使用std::fixed操纵器和std::setprecision对象:

std::cout << "The Percentage is " << std::fixed << setprecision(1) << shootp << '\n';

这将导致21.9的输出。单独使用std::setprecision将导致标准输出2e+01

答案 1 :(得分:3)

您需要在执行输出之前设置精确度

cout << "\nThe Shooting Percentage is " << setprecision(1) << shootp << endl;