简体   繁体   English

我无法获得设置精度以在C ++中工作

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

I can't get the set precision to work in C++. 我无法获得在C ++中工作的设置精度。 I keep getting 3 decimal places instead of 1. If I out 7 and 32 in, shootp comes out as 21.875. 我一直保持小数点后3位而不是1位。如果我分别是7位和32位,那么Shootp的值为21.875。 I need it to come out as 21.9. 我需要它才能成为21.9。 I am fairly new at this and I could use any help! 我在这方面还很陌生,可以使用任何帮助! Thanks 谢谢

#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;       
}

You need to use both std::fixed manipulator and std::setprecision object prior to outputting the floating point variable: 在输出浮点变量之前,您需要同时使用std :: fixed操纵器和std :: setprecision对象:

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

This will result in the output of 21.9 . 这将导致输出21.9 Using std::setprecision alone will result in 2e+01 on standard output. 单独使用std::setprecision将在标准输出上导致2e+01

执行输出之前,需要设置精度。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM