输入一系列数字,计算每个数字出现的次数

程序如下:

#include<iostream>
using namespace std;


int main()
{
    int currval=0, val=0; //currval is the number that we are counting and val is number we enter now
    //reader the first number and ensure there are numbers
    if(cin >> currval){
        int cnt=1;  //保存我们正在处理的数据的次数
        while(cin>> val){  //读取剩余的数 
            if(val==currval){  //如果值相同 
                cnt++;   //将cnt加1 
            } else{    //否则打印前一个值的个数 
                cout<< currval <<" occures " << cnt<<" times"<<endl;
                cnt=1; //重置计数器
                currval=val; //记住新值
            }
        }//while 循环在这里结束
        //记住最后打印文件中最后一个值的次数
        cout<< currval <<" occures " << cnt<<" times"<<endl;  
    }//最外层if在这里结束
    
    return 0;

}

注意:

运行出现的问题:

程序运行输入42 42 42 55 55 62 100 100 100 enter时,出现的结果只包括 42 55 62出现的次数,输入也不会退出,再次键入相同的数字,会一次出现100 42 55 62出现的次数,此处的100应该是上一次键入的100

解决方法:

在键入42 42 42 55 55 62 100 100 100 之后并不直接enter,而是通过Ctrl+Z键入一个^Z(即文件结束符EOF)或者输入一个非整数的字符,再按enter,运行结果就是正确的。(此内容在书上13面介绍,程序在15面)。

猜你喜欢

转载自blog.csdn.net/m0_37698185/article/details/81214943