C++初学者使用序列和浮点
作为一名初级程序员,您将如何进行这项练习?这是一个课堂练习,但我确实想了解最好的方法。
将一系列数字相加需要多长时间才能使总和超过 10000? 打印最后添加的数字以及最终的总和。
这就是我所知道的为简单添加代码编写的内容。在此基础上,您将如何回答上述问题?
#include<iostream>
using namespace std;
int main ()
{
int sum=0;
int n;
for (n=1; n <250; n=n+1)
sum=sum+n;
cout<<"the sum of 1 through 250 is "<<sum<<endl;
return 0;
}
How would you approach this exercise, as a beginning programmer? It is a classroom exercise, but I am truly trying to understand the best approach.
How far do you have to go in adding up a sequence of numbers for the sum to exceed 10000?
Print the last number added, and the final sum.
This is what I know to write for a simple adding code. Building off of this, how would you answer the above problem?
#include<iostream>
using namespace std;
int main ()
{
int sum=0;
int n;
for (n=1; n <250; n=n+1)
sum=sum+n;
cout<<"the sum of 1 through 250 is "<<sum<<endl;
return 0;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以在 for() 语句中添加此条件(总和超过 10000):
一旦
sum >= 10000
循环就会停止,您就会得到答案。您也可以使用 while 循环:甚至
You can just add this condition (sum exceeds 10000) in your for() statement:
as soon as
sum >= 10000
the loop will stop and you have your answer. You can use while loop as well:or even
如果您只需要找到极限值,那么这也许会有所帮助:
If you just need to find the limiting values then perhaps this will help:
因为你希望序列的总和刚好大于 10000。所以这是一个 AP(算术级数)。这样我们就可以实现AP总和的公式了。
即
S = n * [2a + (n-1)*d] / 2
查看以下链接了解详细信息:
http://en.wikipedia.org/wiki/Arithmetic_progression
输入
a=1< /code>、
d=1
和S>10000
让我们取S=10000
n 我们必须找出
方程变为
n^2 + n - 20000 = 0
给出
n = 141
(近似取平方根的 +ve 值)对于任意问题,令 n = X。所以我们可以运行以下循环
sum = X * [2a + (X-1)d] / 2;
上面的循环最多需要 3 次迭代才能找到 X。
这将减少运行循环的开销。例如,如果您有一个更大的总和,例如不是 10000,而是 100000000,那么您将看到执行时间的巨大差异。
Since you want the sum of the sequence to be just more than 10000. So this is an AP (Arithmetic Progression). So we can implement the formula for the sum of a AP.
i.e.
S = n * [2a + (n-1)*d] / 2
check below link for details:
http://en.wikipedia.org/wiki/Arithmetic_progression
Put
a=1
,d=1
andS>10000
let us takeS=10000
n we have to find out
the equation becomes
n^2 + n - 20000 = 0
which gives
n = 141
(approximately taking the +ve value of sq. root)Let n = X for an arbitrary problem. so we can run the following loop
sum = X * [2a + (X-1)d] / 2;
The above loop will take at most 3 iterations to find the X.
it will reduce the overhead of running a loop. e.g. if you have a bigger sum like instead of 10000 let it be 100000000 then you will get to see a huge difference in execution time.
还可以使用高斯公式进行逆向运算,跳过整个循环业务。然后,您将使用浮动和序列,就像您的标题提到的那样。
You can also use Gaus's formula to perform the reverse operation and skip the whole loop business. Then you would be using floats and sequences just as your title mentions.