如何停止循环在C++中添加字符的额外迭代?
因此,我的代码如下:如何停止循环在C++中添加字符的额外迭代?,c++,loops,while-loop,eof,C++,Loops,While Loop,Eof,因此,我的代码如下: if (x > y) { cout << "Sum of the values from " << y << " through " << x << " is: " << endl; while (x >= y) { cout << y << " + "; sum += y; y++; }
if (x > y)
{
cout << "Sum of the values from " << y << " through " << x << " is: " << endl;
while (x >= y)
{
cout << y << " + ";
sum += y;
y++;
}
cout << " = " << sum << endl;
}
执行此操作时,它的末尾有一个额外的加法符号,因此它将输出如下内容:
10+11+12+13+=46
我意识到循环在做什么,它为什么会在末尾添加加法符号对我来说是有意义的,但我不确定该将该语句放在哪里。任何帮助都将不胜感激最简单的解决方案是明确地处理最终案例。即
while (x > y)
{
cout << y << " + ";
sum += y;
y++;
}
cout << y;
sum += y;
cout << "Sum of the values from " << y << " through " << x << " is: " << endl;
while (x > y) //now the last case doesn't go through the loop
{
cout << y << " + ";
sum += y;
y++;
}
cout << y << " = "; //instead it is handled here, and there will be no extra + sign
sum += y;
cout << sum << endl;
\b是一个退格转义序列,你可以用这个来擦除最后的+
if (x > y)
{
cout << "Sum of the values from " << y << " through " << x << " is: " << endl;
while (x >= y)
{
cout << y << " + ";
sum += y;
y++;
}
cout << "\b\b= " << sum << endl; // Change is here...
}
例如,您可以用以下方式编写
do
{
cout << y;
sum += y;
} while ( y++ < x && cout << " + " );
或
或
最简单的方法可能是平底船: 改变
cout << " = " << sum << endl;
在数字更简单之前添加加号:
if (x > y)
{
int sum = y;
cout << "Sum of the values from " << y << " through " << x << " is: " << endl << y;
++y;
while (x >= y)
{
cout << " + " << y ;
sum += y;
y++;
}
cout << " = " << sum << endl;
}
非常感谢。出于某种原因,我只是假设将它置于循环之外会导致它重复,但这是有道理的
cout << " = " << sum << endl;
cout << " 0 = " << sum << endl;
int a[] = {1,2};
int b[] = {1,2,};
if (x > y)
{
int sum = y;
cout << "Sum of the values from " << y << " through " << x << " is: " << endl << y;
++y;
while (x >= y)
{
cout << " + " << y ;
sum += y;
y++;
}
cout << " = " << sum << endl;
}