question: based on the this program (c++), write a program that calculates ? wit
ID: 3554226 • Letter: Q
Question
question: based on the this program (c++), write a program that calculates ? with a desired accuracy.
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
double shoot();
int main()
{
int total, in = 0;
double pi, x, y;
srand((unsigned)time(NULL));
cout << "Enter number of shots: ";
cin >> total;
for (int i=1; i<=total; i++)
{
x = shoot();
y = shoot();
if (x*x+y*y<=1)
in = in + 1;
}
pi = 4*(double)in/total;
cout << "pi = " << pi << endl;
return 0;
}
double shoot()
{
double random_num;
random_num = (double)(rand()%99)/99;
return random_num;
}
Explanation / Answer
#include <iostream>
using namespace std;
int main()
{
int counter = 1;
double odd = 1;
double sum = 0;
int max = 10000;
bool bSign = true;
double pi = 0;
//4-(4/3)+(4/5)-(4/7)+(4/9)-(4/11)+...
do {
if(bSign)
{
pi += 4 / odd;
bSign = false;
}
else
{
pi -= 4 / odd;
bSign = true;
}
odd+=2;
counter++;
sum += pi;
cout << pi << endl;
} while ( counter < max );
cout << "PI : " << (sum / counter) << endl;
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.