3.if条件句--算数字出现次数

Posted foremember

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了3.if条件句--算数字出现次数相关的知识,希望对你有一定的参考价值。

 1 #include <iostream>
 2 
 3 int main()
 4 {
 5     // currVal is the number we‘re counting; we‘ll read new values into val
 6     int currVal = 0, val = 0;
 7 
 8     // read first number and ensure that we have data to process
 9     if (std::cin >> currVal) {
10         int cnt = 1;  // store the count for the current value we‘re processing
11         while (std::cin >> val) { // read the remaining numbers 
12             if (val == currVal)   // if the values are the same
13                 ++cnt;            // add 1 to cnt 
14             else { // otherwise, print the count for the previous value
15                 std::cout << currVal << " occurs "
16                     << cnt << " times" << std::endl;
17                 currVal = val;    // remember the new value
18                 cnt = 1;          // reset the counter
19             }
20         }  // while loop ends here
21         // remember to print the count for the last value in the file
22         std::cout << currVal << " occurs "
23             << cnt << " times" << std::endl;
24     } // outermost if statement ends here
25     system("pause");
26     return 0;
27 }

输入:111 111 111 111 22 22 22 22 34 444 444 777 777 (回车)

得到:

技术图片

还在等着键盘的输入。

 

原因:cin没有遇到end-of-file

输入:111 111 111 111 22 22 22 22 34 444 444 777 777 (ctrl + Z)(回车)
得到:

技术图片

结果正常

 

以上是关于3.if条件句--算数字出现次数的主要内容,如果未能解决你的问题,请参考以下文章

控制语句

Javascript流程控制

如何用Python统计《论语》中每个字的出现次数?10行代码搞定--用计算机学国学

java 基础 - 查找某个字串出现的次数及位置

python第二天

查找输入字符串中出现字符次数最多的那个字和重复次数