C++primer第五版 统计在输入中每个值连续出现的次数

// primer_1_4_4.cpp : Defines the entry point for the application.
// 统计在输入中每个值连续出现的次数

#include "stdafx.h"
#include<iostream>
using namespace std;

int main()
{
	int currVal=0, val=0;  //currVal为当前正在统计的数,val为读入的新值
	cout << "input the numbers: (end with 'q')" << endl;  //提示用户输入一串数据,输入完成后以'q'结束
	if(cin >> val)  //检测是否有数据
	{
		int count=1; //count用于记录某个数据连续出现的次数,检测到有数据时,该数据已经出现一次,因此赋初值为1
		currVal=val; //当前正在统计的数据为第一个输入的数据
		while(cin >> val) //读取剩余的数据
		{
			if(currVal==val)  //如果新数据的值和前一个数据值相同
				count++;  //则计数变量加1
			else  //如果新数据的值和前一个数据值不同
			{
				cout << currVal << " occurs " << count << " times." << endl; //则先输出前一数据的统计结果
				currVal=val;  //再将新值赋给currVal,继续统计
				count=1; //计数变量重新赋值为1(新值统计)
			}
		}
		cout << currVal << " occurs " << count << " times." << endl; //记得打印文件中最后一个值的个数
	}
	system("pause");
	return 0;
}

程序已经注释得很清楚了,这里就不再累述。不过要特别提醒几点。

1. 输入完一串数据后,要以q结尾(或者以其它非int类型的输入结尾),不然最后一部分相同的数据的统计结果显示不出来;

2. 为了最后能显示出最后一个值的个数,需要在while循环外写上打印语句。

cout << currVal << " occurs " << count << " times." << endl; //记得打印文件中最后一个值的个数

则,输入一串数据:12 12 12 45 45 67 67 67 23 45 q,敲回车

则输出:

12 occurs 3 times.
45 occurs 2 times.
67 occurs 3 times.
23 occurs 1 times.
45 occurs 1 times.

即效果如下:

如果全是相等的值或者没有重复值,输出会怎样呢?

扫描二维码关注公众号,回复: 2943631 查看本文章

也是可以正常运行的。

猜你喜欢

转载自blog.csdn.net/elma_tww/article/details/82115240