理解循环C++中的循环
Understanding loops within loops C++
对新手的问题表示歉意,但我对编程和学习C++还很陌生。我正在学习C++初级教程,现在已经到了编写这段代码的If语句部分。
#include <iostream>
int main()
{
// currVal is the number we're counting, new values will be put into val
int currVal = 0, val = 0;
// Read first number and check there is data to process
if (std::cin >> currVal) {
int cnt = 1; // Store the count for the current value we're processing
while (std::cin >> val) { // read the remaining numbers
if (val == currVal) // if the values are the same
++cnt; // add 1 to count (cnt)
else { // Otherwise, print the count for the previous value
std::cout << currVal << " occurs " << cnt << " timesn";
currVal = val; // remember the new value
cnt = 1; // reset the counter
}
} // while loop ends here
// rememeber to print the count for the last value in the flile
std::cout << currVal << " occurs " << cnt << " times.n";
} // Outermost if statement ends here
return 0;
}
编译时,逻辑不正确。例如,当我输入51 25 14 51 51 25时。我得到以下信息:
51发生1次25发生1次14发生1次51发生3次
我试过分解代码,但循环中有循环,这让我头疼。
再次为noob问题道歉,但如有任何帮助,我们将不胜感激。
感谢
您的代码:
if (std::cin >> currVal) {
int cnt = 1; // Store the count for the current value we're processing
while (std::cin >> val) { // read the remaining numbers
if (val == currVal) // if the values are the same
++cnt; // add 1 to count (cnt)
else { // Otherwise, print the count for the previous value
std::cout << currVal << " occurs " << cnt << " timesn";
currVal = val; // remember the new value
cnt = 1; // reset the counter
}
}
上面写着cin>gt;currval,这基本上意味着如果您正在输入一个值,请执行以下操作。它经历了第一次,然后你进入while循环,它基本上说,当你还有输入时,如果val=currVal增加cnt,否则就在else块中做。你有7个输入,所以循环进行了7次,这有什么令人困惑的??
相关文章:
- 如何循环打印顶点结构
- 如何在C++中从两个单独的for循环中添加两个数组
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 正在尝试了解输入验证循环
- std::map<struct,struct>::find 找不到匹配项,但是如果我循环通过 begin() 到 end(),我在那里看到匹配项
- 循环后如何继续阅读
- Ardunio UNO解决了多个重叠的定时器循环
- Eigen如何在容器循环中干净地附加矩阵
- 在某些循环内使用vector.push_back时出现分段错误
- 我正在使用嵌套的while循环来解析具有多行的文本文件,但由于某种原因,它只通过第一行,我不知道为什么
- 为什么我的for循环不能正确获取argv
- 如何声明特征矩阵,然后通过嵌套循环初始化它
- while循环中while循环的时间复杂度是多少
- C++中的高效循环缓冲区,它将被传递给C样式数组函数参数
- 为什么在这个代码结束循环中没有得到结束
- 在基于范围的for循环中使用结构化绑定声明
- 用于C++中带有数组和指针的循环
- 循环中的随机函数
- 是什么阻止DOMTimerCoordinator::NextID进入无休止的循环
- 在循环C++中指定字符串之后,不会打印该字符串