码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2019-03-04 14:25:08      阅读:174      评论:0      收藏:0      [点我收藏+]

标签:oop   ISE   ESS   class   ast   state   ctr   -o   ber   

 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条件句--算数字出现次数

标签:oop   ISE   ESS   class   ast   state   ctr   -o   ber   

原文地址:https://www.cnblogs.com/foremember/p/10470331.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!