Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/129.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何停止循环在C++中添加字符的额外迭代?_C++_Loops_While Loop_Eof - Fatal编程技术网

如何停止循环在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;
}