Cout long double issue

前端 未结 4 1614
一向
一向 2021-01-14 06:01

So, I\'m working on a C++ project. I have a var of long double type and assigned it a value like \"1.02\"

Then, I try to use cout to print it and the result is: -0

4条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-14 06:28

    I see nothing wrong at all in the code. I just put it into a standard format and it works. Here is the code assuming what you posted is the entire thing.

    #include 
    
    using namespace std;
    
    int main(){
        long double var = 1.0202;
        cout.precision(5);
        cout << var << endl;
    }
    

    I hope this answers your question.

    Edit: P.S. Shorter, the better, so I have a better solution (opinionated).

    #include 
    #include 
    using namespace std;
    
    int main(){
        long double var = 1.0202;
        //cout.precision(5);
        cout << setprecision(5) << var << endl;
    }
    

    I think this one is better since it is shorter. I would also recommend using printf if you are doing more complex decimal stuff since printf can choose which variables (if you have multiple) have decimals or how much.

提交回复
热议问题