How to use setprecision in C++

前端 未结 7 1547
遇见更好的自我
遇见更好的自我 2020-11-27 05:38

I am new in C++ , i just want to output my point number up to 2 digits. just like if number is 3.444, then the output should be 3.44 o

相关标签:
7条回答
  • 2020-11-27 06:19

    Replace These Headers

    #include <iomanip.h>
    #include <iomanip>
    

    With These.

    #include <iostream>
    #include <iomanip>
    using namespace std;
    

    Thats it...!!!

    0 讨论(0)
  • 2020-11-27 06:25
    #include <iostream>
    #include <iomanip>
     
    int main(void) 
    {
        float value;
        cin >> value;
        cout << setprecision(4) << value;
        return 0;
    }
    
    0 讨论(0)
  • 2020-11-27 06:27
    #include <iomanip>
    #include <iostream>
    
    int main()
    {
        double num1 = 3.12345678;
        std::cout << std::fixed << std::showpoint;
        std::cout << std::setprecision(2);
        std::cout << num1 << std::endl;
        return 0;
    }
    
    0 讨论(0)
  • 2020-11-27 06:28

    The answer above is absolutely correct. Here is a Turbo C++ version of it.

    #include <iomanip.h>
    #include <iostream.h>
    
    void main()
    {
        double num1 = 3.12345678;
        cout << setiosflags(fixed) << setiosflags(showpoint);
        cout << setprecision(2);
        cout << num1 << endl;
    }
    

    For fixed and showpoint, I think the setiosflags function should be used.

    0 讨论(0)
  • 2020-11-27 06:34
    #include <bits/stdc++.h>                        // to include all libraries 
    using namespace std; 
    int main() 
    { 
    double a,b;
    cin>>a>>b;
    double x=a/b;                                 //say we want to divide a/b                                 
    cout<<fixed<<setprecision(10)<<x;             //for precision upto 10 digit 
    return 0; 
    } 
    

    input: 1987 31

    output: 662.3333333333 10 digits after decimal point

    0 讨论(0)
  • 2020-11-27 06:35
    #include <iostream>
    #include <iomanip>
    using namespace std;
    

    You can enter the line using namespace std; for your convenience. Otherwise, you'll have to explicitly add std:: every time you wish to use cout, fixed, showpoint, setprecision(2) and endl

    int main()
    {
        double num1 = 3.12345678;
        cout << fixed << showpoint;
        cout << setprecision(2);
        cout << num1 << endl;
    return 0;
    }
    
    0 讨论(0)
提交回复
热议问题