计算数组中元素重复的次数 [英] Count how many times elements in an array are repeated

查看:67
本文介绍了计算数组中元素重复的次数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要编写的程序允许我输入10个数字,它应该告诉我数字X重复X次,依此类推.

The program I'm trying to write allows me to enter 10 numbers and it should get tell me Number X is repeated X times and so on.

我一直在尝试,但是问题是我得到的结果如下:

I've been trying this but the problem is I get the result as follows:

例如... {1,1,1,1,4,6,4,7,4}

For example...{1,1,1,1,4,6,4,7,4}

数字1重复4次

数字1重复3次

数字1重复2次

数字1重复1次

数字4重复3次

数字6重复1次

数字4重复2次

数字7重复1次

数字4重复1次

问题在于,它会检查具有以下编号的下一个编号,而不会跳过该编号,或者不知道它之前已经写入了该编号

The problem is that it checks the next number with the following numbers without skipping it, or without knowing it has written it before

#include <iostream>
#include <string>
using namespace std;
int main() {
    int x[10];
    for (int i=0;i<10;i++) {
        cin>>x[i];
    }

    for (int i=0;i<9;i++) {
        int count=1;
        for (int j=i+1;j<10;j++) { 
            if (x[i]==x[j]) count++;
        }
        cout<<"The number "<<x[i]<<" is repeated "<<count<<" times"<<"\n";
    }
}

推荐答案

代码的问题是您重新处理已经处理过的数字.因此,如果在位置0出现 1 ,在位置5再次出现 1 ,那么您将在位置5处理 1 当您到达循环中时再次出现.

The problem with your code is that you re-process numbers that you've already processed. So if there is an occurrence of 1 at position 0 and another occurrence of 1 at position 5, then you will process the 1 at position 5 again when you get there in the loop.

因此,您需要一种方法来确定号码是否已被处理.一种简单的方法是添加第二个数组(最初所有值都设置为0),并且每当处理一个数字时,都标记该元素出现的所有位置.现在,在处理元素之前,请检查该元素是否已被处理,如果是这种情况,则什么也不做.

So you need a way to decide if a number has been processed already or not. An easy way is to add a second array (initially all values are set to 0) and whenever you process a number you mark all positions where that element occurs. Now before processing an element you check if it's been processed already and do nothing if that's the case.

此外,尝试正确缩进代码:)

Also, try to indent your code properly :)

C ++代码:

int main( void ) {
    const int N = 10;

    int A[N];
    for(int i = 0; i < N; i++)
        cin >> A[i];

    int seen[N];
    for(int i = 0; i < N; i++)
        seen[i] = 0;

    for(int i = 0; i < N; i++) {
        if(seen[i] == 0) {
            int count = 0;
            for(int j = i; j < N; j++)
                if(A[j] == A[i]) {
                    count += 1;
                    seen[j] = 1;
                }
            cout << A[i] << " occurs " << count << " times" << endl;
        }
    }

    return 0;
}

这篇关于计算数组中元素重复的次数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆