我想计算以下系列的总和:
5 + 8 + 11 + .... + 50
我希望使用for循环来打印上面的系列和系列的总和。我写了以下代码:
#include <iostream>
using namespace std;
int main()
{
int i, sum = 0, n = 50;
cout << "\n\n THE SERIES IS UNDER : \n\n\n";
i = 2;
while(i <= n)
{
sum = sum + i;
if (i == 2)
cout << i;
else
cout << " + "<< i;
i = i + 3;
}
cout << "\n\n\n THE SUMMATION IS "<< sum;
return 0;
}
答案 0 :(得分:3)
cout<<"\n\n\n THE SUMMATION IS ",sum;
- &GT;
cout << "\n\n\n THE SUMMATION IS " << sum;
和
cout<<" + ",i;
- &GT;
cout << " + " << i;
逗号(,
)运算符在此处不像流(<<
)运算符那样工作。
答案 1 :(得分:3)
#include<iostream>
using namespace std;
int main()
{
cout << "\n\n THE SERIES IS UNDER : \n\n\n";
int sum = 0;
for (int i = 5; i < 50; i += 3) {
cout << i << '+';
sum += i;
}
cout << 50 << endl;
sum += 50;
cout << "\n\n\n THE SUMMATION IS " << sum << endl;
return 0;
}
此版本的变化:
iostream
代替iostream.h
; this is more portable between compilers for
循环更简洁明了。if (i == 2) cout << i;
是浪费时间,因为它只适用于一次迭代。相反,您可以将第一项或最后一项作为for
循环之外的特殊情况处理。sum += i
代替sum = sum + i
,因为前者更清晰有效。大多数程序员默认会选择前者。cout << endl
。 '\n'
和endl
之间存在差异,除非您有理由不这样做。请参阅帖子:C++: "std::endl" vs "\n"