I have a program here to approximate the value of pi using a series, and need it to output pi to a certain degree of accuracy, I have chosen 16 digits. However, when I input 0 for the summation, it returns 4 (which is the correct answer) but with no decimals. The rest of my inputs result in a precision of 16.
#include <iostream>
#include <iomanip>
#include <string>
using std::cin;
using std::cout;
using std::endl;
int myPrompt(void);
double mySum(int);
void myResults(void);
int main() {
myResults();
return 0;
}
int myPrompt(void) {
cout << "Approximating pi using the Madhava-Leibniz series" << endl
<< std::setfill('=') << std::setw(std::size("Approximating pi using the Madhava-Leibniz series")) << "" << endl;
int input;
do {
cout << "Please input an integer greater than or equal to 0: ";
cin >> input;
} while (input < 0);
return input;
}
double mySum(int input) {
double numerator = -1;
double output = 0;
int base = -1;
for (int k = 0; k <= input; k++) {
numerator *= base;
output += numerator / ((2 * k) + 1);
}
return (output * 4);
}
void myResults(void) {
int userInput = myPrompt();
double output = mySum(userInput);
cout << std::setprecision(16) << "The approximated value of pi is: " << output << endl;
}
I tried setting multiple variable types to double assuming it was just returning an integer, but I can't seem to find why. I just need it to output 4 with 16 digits of accuracy. Any help is appreciated, thank you!
I think the problem is how std::cout
displays floating-point numbers. When you set the precision using std::setprecision(16)
, it affects the number of decimal places displayed, but it doesn't guarantee that all 16 decimal places will be shown if they are zeros.
You can use std::fixed
and std::showpoint
in addition to setting the precision:
void myResults(void) {
int userInput = myPrompt();
double output = mySum(userInput);
cout << std::fixed << std::showpoint << std::setprecision(16) << "The approximated value of pi is: " << output << endl;
}