如何使用“For”进行打印 [英] How Can I Print With "For"
问题描述
所以最后结果不是我想要的,在第一个数字之后还有一个额外的+不应该在那里,我怎么能解决这个问题,请帮帮我
________________________________
So at the end the result is not what i want, there is an extra "+" after the first number which shouldnt be there, how can I solve this problem, please help me out
________________________________
#include <iostream>
using namespace std;
void main(){
system("color b");
int cont = 0, b;
cout << "insert N; ";
cin >> b;
cout << "the sum is ";
for (int a = 1; a <= b; a += 2){
cont = a + cont;
cout << " + " << a;
}
cout << " = " << cont << endl;
system("pause");
}
_________________________________
_________________________________
Insert; 10
The sum is + 1 + 3 + 5 + 7 + 9 = 25
推荐答案
查看@pwasser的评论。
检查行
See the comment from @pwasser.
Examine the line
cout << " + " << a;
注意额外的+是之前第一个数字不是之后
考虑如何在循环的第一次迭代中不打印+。
我再次推荐你来自pwasser的评论...
Note that the extra "+" is before the first number not after it
Consider how you might not print that "+" on the first iteration of the loop.
I refer you again to the comment from pwasser...
尝试一下。逐步完成循环,看看发生了什么
Try a bit harder. Step through your loop and see what is happening
for (c = 2; c <= (a * 2); c += 2){
cout << c;
if (c < (a * 2)) cout << "+";
}
最后,omfg我终于明白了它是如何工作的:P,谢谢
finally, omfg I finally understood how that works :P, thanks
这篇关于如何使用“For”进行打印的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!