使用 C++ for 循环估算圆周率
Estimating pi with c++ for loop
我正在尝试使用 for 循环来近似圆周率。用户输入迭代次数 n,程序应该在每次额外的迭代中获得一个越来越准确的 pi 值。我有一个嵌套的 "if" 控制结构,用于检查 "i" 是偶数还是奇数。但是,当我的循环在第一个 运行 之后重复时,我的 pi 值没有改变。 Pi 在循环中保持在 1,最终输出为 4。我必须使用近似级数:
pi = 4[ 1 - 1/3 + 1/5 +...+ 1/(2n-1) + 1/(2n+1) ]。
我做错了什么?
int _tmain(int argc, _TCHAR* argv[])
{
double pi = 0;
long i;
int n;
cout << "Enter the value of n: "; //prompt for input
cin >> n; //store input in "n"
cout << endl; //end line
for (i = 0; i < n; i++)
{
if (i % 2 == 0) //if even
pi = pi + (1 / (2 * i + 1));
else //if odd
pi = pi - (1 / (2 * i + 1));
}
pi = 4 * pi; //multiply by 4
cout << endl << "pi = " << pi << endl; //display result
system("Pause"); //pause program
return 0; //close program
问题是您在计算浮点数时使用了 ints
。在这里阅读:Why can't I return a double from two ints being divided
因此,为避免这种情况,您需要使用浮点数进行数学计算:
pi = pi + (1.0 / (2.0 * i + 1.0));
事实上,在您打算使用浮点数时始终明确指定是个好主意,即使这是不必要的:
const float pi_real = 3.14159;
const float one = 1.0;
这样可以明确你的意图,避免类似这样的错误。 Here is a live example.
我正在尝试使用 for 循环来近似圆周率。用户输入迭代次数 n,程序应该在每次额外的迭代中获得一个越来越准确的 pi 值。我有一个嵌套的 "if" 控制结构,用于检查 "i" 是偶数还是奇数。但是,当我的循环在第一个 运行 之后重复时,我的 pi 值没有改变。 Pi 在循环中保持在 1,最终输出为 4。我必须使用近似级数:
pi = 4[ 1 - 1/3 + 1/5 +...+ 1/(2n-1) + 1/(2n+1) ]。
我做错了什么?
int _tmain(int argc, _TCHAR* argv[])
{
double pi = 0;
long i;
int n;
cout << "Enter the value of n: "; //prompt for input
cin >> n; //store input in "n"
cout << endl; //end line
for (i = 0; i < n; i++)
{
if (i % 2 == 0) //if even
pi = pi + (1 / (2 * i + 1));
else //if odd
pi = pi - (1 / (2 * i + 1));
}
pi = 4 * pi; //multiply by 4
cout << endl << "pi = " << pi << endl; //display result
system("Pause"); //pause program
return 0; //close program
问题是您在计算浮点数时使用了 ints
。在这里阅读:Why can't I return a double from two ints being divided
因此,为避免这种情况,您需要使用浮点数进行数学计算:
pi = pi + (1.0 / (2.0 * i + 1.0));
事实上,在您打算使用浮点数时始终明确指定是个好主意,即使这是不必要的:
const float pi_real = 3.14159;
const float one = 1.0;
这样可以明确你的意图,避免类似这样的错误。 Here is a live example.