我无法使设置的精度在C++

I can't get the set precision to work in C++

本文关键字:精度 C++ 设置      更新时间:2023-10-16

我无法在C 中工作。我不断获得3个小数的位置,而不是1。如果我7和32英寸,Shootp的出现为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;       
}

您需要同时使用std ::固定操纵器和std :: setPrecision对象,然后再输出浮点变量:

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

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

您需要在之前设置Precision 您执行输出。

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