C ++初学者使用序列和浮点数

时间:2012-02-07 07:19:34

标签: c++ floating-point points

作为一名初学程序员,您将如何处理此练习?这是一个课堂练习,但我真的想要了解最好的方法。

你需要在多长时间内将一系列数字加起来超过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;
}

4 个答案:

答案 0 :(得分:4)

您可以在for()语句中添加此条件(总和超过10000):

int sum=0;
for (int n=1; sum < 10000; n++)
    sum += n;

cout << "the sum of 1 through " << n-1 <<  " is " << sum << endl;

只要sum >= 10000循环停止并且您有答案。您也可以使用while循环:

int sum=0, n = 0;
while (sum < 10000) {
    n++;
    sum += n;
}  
cout << "the sum of 1 through " << n <<  " is " << sum << endl;

甚至

int sum=0, n = 0;
while ( (sum += ++n) < 10000 ) ;

cout << "the sum of 1 through " << n <<  " is " << sum << endl;

答案 1 :(得分:3)

如果您只是需要找到限制值,那么这可能会有所帮助:

#include<iostream>
using namespace std; 
int main () 
{
int sum=0; 
int n=1;
while(sum<=10000){
sum=sum+n;
n++;
}
cout<<”to get 10000 you have to add till “<<n<<endl;
return 0;
}

答案 2 :(得分:3)

因为您希望序列的总和大于10000.所以这是一个AP(算术级数)。所以我们可以实现AP总和的公式。

即。 S = n * [2a + (n-1)*d] / 2 请查看以下链接了解详情:
http://en.wikipedia.org/wiki/Arithmetic_progression

a=1d=1S>10000放到S=10000上 我们必须找出

等式成为 n^2 + n - 20000 = 0

给出了 n = 141(大约取平方根的+ ve值)

对于任意问题,设n = X.所以我们可以运行以下循环

sum = X * [2a +(X-1)d] / 2;

if(sum <= 10000)
   while(sum < 10000 && (++X))
      sum = X * [2a + (X-1)d] / 2;
else
   while(sum > 10000 && (--X))
      sum = X * [2a + (X-1)d] / 2;

cout << "We should continue the sequence up to" << X;

上述循环最多需要3次迭代才能找到X.

它将减少运行循环的开销。例如如果你有一个更大的总和,而不是10000让它是100000000那么你会看到执行时间的巨大差异。

答案 3 :(得分:1)

您还可以使用Gaus's formula执行反向操作并跳过整个循环业务。然后你会像你的标题一样使用浮点数和序列。