ccsmiles 于 2016.02.16 23:02 提问

#include "stdafx.h"
#include
using namespace std;

int main()
{
double arctan(double);
cout << "pi= " << 16 * arctan(1 / 5.0) - 4 * arctan(1 / 239.0) << endl;
return 0;
}

double arctan(double x)
{
double result = 0;
int i = 1, k = 1;
do
{
for (k = 1; k <= (2 * i - 1); k++)
k *= x;
switch (i % 2)
{
case 1:
result += (k / (2 * i - 1)); break;
case 0:
result -= (k / (2 * i - 1)); break;
}
i++;
} while (k > 1e-15);
return result;
}

8个回答

caozhy      2016.02.16 23:13

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

double arctan(double);

int main()
{
cout << "pi= " << 16 * arctan(1 / 5.0) - 4 * arctan(1 / 239.0) << endl;
return 0;
}

double arctan(double x)
{
double result = 0;
int i = 1, s = 1;
double k = 1.0;
do
{
double t = 1;
for (int j = 0; j < (i * 2 - 1); j++)
t *= x;
k = t / (double)(i * 2 - 1) * (double)s;
result = result + k;
s = -s;
i++;
} while (k > 1e-15);
return result;
}
``````
ccsmiles 谢谢您的热心回答，我按您说的，改正了数据类型，结果变成3.17473，原题答案是3.1415

caozhy      2016.02.16 23:13

pi= 3.1406

VisualEleven      2016.02.17 15:27

ccsmiles 谢谢关注！代码贴在下面：

ccsmiles   2016.02.18 09:58
`````` #include "stdafx.h"
#include<iostream>
using namespace std;

double arctan(double);

int main()
{
double a = 16 * arctan(1 / 5.0);
double b = 4 * arctan(1 / 239.0);
cout << "pi= " << a-b << endl;
return 0;
}

double arctan(double x)
{
double result = 0;
int i = 1, j = 1;
double k = 1;
do
{
for (j = 1; j <= (2 * i - 1); j++)
k *= x;
switch (i % 2)
{
case 1:
result += (k / (2 * i - 1)); break;
case 0:
result -= (k / (2 * i - 1)); break;
}
i++;
} while (k > 1e-15);
return result;
}
``````
ccsmiles   2016.02.18 09:59
`````` #include "stdafx.h"
#include<iostream>
using namespace std;

double arctan(double);

int main()
{
double a = 16 * arctan(1 / 5.0);
double b = 4 * arctan(1 / 239.0);
cout << "pi= " << a-b << endl;
return 0;
}

double arctan(double x)
{
double result = 0;
int i = 1, j = 1;
double k = 1;
do
{
for (j = 1; j <= (2 * i - 1); j++)
k *= x;
switch (i % 2)
{
case 1:
result += (k / (2 * i - 1)); break;
case 0:
result -= (k / (2 * i - 1)); break;
}
i++;
} while (k > 1e-15);
return result;
}
``````
ccsmiles   2016.02.18 10:00

vs2015运行的结果怎么是3.17473？

ccsmiles   2016.02.18 10:00

vs2015运行的结果怎么是3.17473？

ccsmiles   2016.02.18 10:22

`````` #include "stdafx.h"
#include <iostream>

using namespace std;

double arctan(double x) {
double sqr = x * x;
double e = x;
double r = 0;
int i = 1;
while (e / i > 1e-15) {
double f = e / i;
r = (i % 4 == 1) ? r + f : r - f;
e = e * sqr;
i += 2;
}
return r;
}

int main() {
double a = 16.0 * arctan(1 / 5.0);
double b = 4.0 * arctan(1 / 239.0);
cout << "PI = " << a - b << endl;
return 0;
}
``````