简体   繁体   中英

How can I print the result from this code with four places after the decimal point?

How can I print the result with four places after the decimal point?

#include <iostream>
#include <math.h>

using namespace std;

int main() {
    double A;
    double R;
    cin >> R;
    A = 3.14159 * R * R;
    cout << "A=" << A << "\n";

    return 0;
}
#include <iostream>
#include <math.h>
#include <iomanip>
using namespace std;

int main() {

    double A;
    double R;
    cin >> R;
    A = 3.14159*R*R;
    cout << "A="<< fixed << setprecision(4) << A<< "\n";

    return 0;
}

Add the library iomanip. fixed and setprecision are utilized in this case to achieve your goal of printing out up to 4 decimal points.

Please consider the following approach. As many will tell you, avoid using using namespace std; . As great explanation for it can be found here

#include <iostream>
#include <math.h>

int main(){

    double A;
    double R;
    char buffer[50] = {};    // Create a buffer of enough size to hold the output chars

    std::cout << "Enter a number >> "; std::cin >> R;
    A = 3.141519*R*R;
    sprintf(buffer, "A = %.4f\n", A);    // Here you define the precision you asked for
    std::cout << buffer;

    return 0;

}

where the output is:

Enter a number >> 56

 A = 9851.8036

You can run it here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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