如何在C++中阻止循环添加额外的字符迭代
How do you stop a loop from adding an extra iteration of a character in C++?
所以我的代码如下:
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...
}
相关文章:
- 在迭代期间添加到 std::unordered_set(或 unordered_map)中的元素是否会在迭代期间访问?
- 需要循环帮助以迭代方式添加到程序集中的总和变量
- 是否可以使用OpenMP并行化一个列表,该列表可以在每次迭代中添加新元素
- 将 char* 推送到矢量时出现问题,但在每次迭代后,它会将指向相同值缓冲区的指针添加到矢量中
- 当迭代器添加到添加到列表向量的结构时,迭代器停止指向值?
- 如何将最终迭代添加到 while 循环
- 在向量上迭代,并添加迭代器实际指向的对象作为映射中的键
- 在迭代时,将元素添加到向量中
- 在迭代地图时向/从地图添加/删除元素是否安全
- 如何在向列表中添加项目的同时迭代列表
- 如何使用分治和迭代器添加所有向量元素
- boost图库图的构建;迭代地添加边属性
- 添加元素时,c++ 中的矢量迭代器是否会损坏
- 添加要迭代设置的元素
- 如何在迭代列表时最小化互斥锁,同时能够添加来自另一个线程的元素
- 如何在C++中阻止循环添加额外的字符迭代
- 迭代地向二叉树中添加一个新节点,根被覆盖
- C++迭代程序-为什么我必须添加.begin()才能获得二进制搜索的中点
- 使用迭代器和擦除/添加项遍历QMap是否正确
- 使用迭代器向std::vector对象添加其自身的元素