问题描述
- 求助:c++求pi,编译通过,但运行后无任何结果?
-
#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;
}
解决方案
#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;
}
解决方案二:
pi= 3.1406
解决方案三:
什么无结果?你是怎样运行的?
解决方案四:
#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;
}
解决方案五:
#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;
}
解决方案六:
vs2015运行的结果怎么是3.17473?
解决方案七:
vs2015运行的结果怎么是3.17473?
解决方案八:
答案是这样的:
#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;
}
时间: 2024-10-31 04:59:24