how can I print the result from this c code 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;
}
CodePudding user response:
#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.
CodePudding user response:
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