gpt4 book ai didi

c++ - 了解循环C++中的循环

转载 作者:行者123 更新时间:2023-12-02 10:29:41 24 4
gpt4 key购买 nike

为新手问题道歉,但是我是编程和学习C++的新手。我正在通过C++ Primer进行工作,并且已经进入了编写此代码的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 << " times\n";
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 51 25时,我得到以下信息:
51次出现1次
25次发生1次
14次发生1次
51次出现3次
我曾尝试分解代码,但是在循环中使用循环会使我头晕。
再次,对菜鸟问题表示歉意,但任何帮助将不胜感激。
谢谢

最佳答案

您的代码:

 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 << " times\n";
currVal = val; // remember the new value
cnt = 1; // reset the counter
}
}
它说cin >> currval,这基本上意味着如果您输入一个值,请执行以下操作。它是第一次执行,然后进入while循环,该循环基本上说您仍然有输入,如果val == currVal增加cnt,否则在else块中执行操作。您有7个输入,因此循环执行了7次,这有什么令人困惑的地方?

关于c++ - 了解循环C++中的循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62784428/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com