gpt4 book ai didi

c++ - 如何重置for循环中的值?

转载 作者:行者123 更新时间:2023-11-30 03:40:12 27 4
gpt4 key购买 nike

我需要帮助找出我的代码哪里出错了。我想重置循环的值,以便它不会编译,因为我现在的输出在当前计算中使用过去的输入值,而我希望输出每次都不同,就好像这是第一次运行代码一样。当我不使用 while 循环时代码工作正常,但每次我都必须重新运行程序。我希望输出每次都提示新输入,但不在新计算中使用过去的输入。我知道我解释得不是很好,但我有点迷路了。任何帮助!

这是我的问题:

An approximate value of pi can be calculated using the series given below:

pi = 4 · [ 1 – 1/3 + 1/5 – 1/7 + 1/9 ... + (–1 ^ n)/(2n + 1) ]

Write a C++ program to calculate the approximate value of pi using this series. The program takes an input n that determines the number of terms in the approximation of the value of pi and outputs the approximation. Include a loop that allows the user to repeat this calculation for new values n until the user says she or he wants to end the program.

#include <cstdio>
#include <iostream>

using namespace std;

int main()
{
int n;
double sum=0;

cout << "Enter the number of terms to approximate (or zero to quit):\n";
cin >> n;

if (n == 0)
{
return 0;
}

while (n != 0)
{
{ for(int i=0;i<n;i++)
{
if (i%2==0)
{
sum += 1.0/(2*i+1);
}
else
{
sum += -1.0/(2*i+1);
}
}

cout.setf(ios::showpoint);
cout.precision(3);
cout << "The approximation is " << sum*4 << " using " << n << " terms." << endl;
}
cout << "Enter the number of terms to approximate (or zero to quit):\n";
cin >> n;
}

return 0;
}

这是我的输出:

输出应该是这样的:

最佳答案

在进入for 循环之前,您不要重置sum。只需添加

sum=0;

for 行之前。

关于c++ - 如何重置for循环中的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38216644/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com