如何在C++中阻止循环添加额外的字符迭代

How do you stop a loop from adding an extra iteration of a character in C++?

本文关键字:添加 迭代 字符 循环 C++      更新时间:2023-10-16

所以我的代码如下:

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

我意识到这个循环在做什么,它为什么会在末尾添加加号对我来说是有道理的,但我不确定该把这个语句放在哪里。如有任何帮助,将不胜感激

最简单的解决方案是显式处理最终情况。即

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;
 while (x > y)
{
    cout << y << " + ";
    sum += y;
    y++;
} 
cout << y;
sum += y;

最简单的方法可能是下注:

更改

cout << " = " << sum << endl;

cout << " 0 = " << sum << endl;

这就是为什么在C和C++中都允许这些:

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;
}

例如,您可以用以下方式编写

do
{
    cout << y;
    sum += y;
} while ( y++ < x && cout << " + " );

while (x >= y)
{
    cout << y;
    if ( x != y ) cout << " + ";
    sum += y++;
} 

while (x >= y)
{
    cout << y << ( x == y ? " = " : " + " );
    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 << "bb= " << sum << endl;     // Change is here...
}