如何查找一个数字在数组中重复多少次? [英] How to find how many times a number has been repeated in an array?

查看:109
本文介绍了如何查找一个数字在数组中重复多少次?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很困惑如何找出用户输入中数字被重复多少次.我能够输入数字,并查看哪些数字在重复,但是不确定如何打印出每个输入的数字以及该数字使用了多少次.这就是我到目前为止

I am confused how to find out how many times a number has been repeated in a user input. I am able to input numbers and see which numbers are repeating but am unsure of how to print out each inputed number and how many times that number was used. This is what I have so far

#include <stdio.h>
#include <stdlib.h>

int main(){

    double numArray[100];
    int x = 0;
    int y = 0;
    int counter = 1;
    int count = 0;

    setvbuf(stdout, NULL, _IONBF, 0);

    printf("Enter any number of integers between 0 and 99 followed a non-numeric: \n");

    for (x = 0; x < 100; x++) {
        if (scanf("%lf", &numArray[x]) != 1)
            break;
        counter = counter + 1;
    }
    counter = counter - 1;

    for(x = 0; x < counter; x++){
        for(y = x + 1; y < counter; y++){
            if(numArray[x] == numArray[y]){
                printf("duplicate found: %lf\n", numArray[x]);
                break;
            }
        }
    }

    return EXIT_SUCCESS;
}

推荐答案

继续我的初始评论,每当您要捕获某个范围内的值的频率时,通常都需要声明一个数组并让该数组的每个元素表示范围内的一个值. (这适用于整数输入).例如,在您的情况下,如果要查找用户在0-99范围内输入的整数值的频率,则可以声明一个包含100个元素的数组(表示值0-99),并将所有值初始化为0. [1]

Continuing for my initial comment, whenever you want to capture the frequency of values within a range, you generally want to declare an array and let each element of the array represent one value within the range. (this applies to integer input). For example, in your case, if you want to find the frequency of the integer values entered by a user in the range of 0-99, you would declare an array with 100 elements (representing values 0-99) and initialize all values to 0.[1]

然后,每当用户输入范围内的有效值时,便会递增该元素.例如,如果您的用户输入58,则可以增加array[58] = array[58] + 1;(或简称为array[58]++;). array[58]的值现在为1,表示用户已输入58一次. (如果再次输入58,则为2,依此类推...)

Then each time the user enters a valid value in the range, you increment that element. For example, if your user enters 58, you would increment array[58] = array[58] + 1; (or simply array[58]++;). The value of array[58] is now 1 indicating the user has entered 58 once. (if 58 was entered again, it would be 2, and so on...)

这很适合您的输入循环.您只需声明说int x;并在scanf调用中填写x,确认它在范围内,然后array[x]++;例如,将您的numarray声明为int [100],则可以执行 [2] :

This lends itself nicely for your input loop. You simply declare say int x; and in your scanf call, you fill x, validate it is within the range and then array[x]++; For example with your numarray declared as int [100], you could do [2]:

#define NMAX 100  /* define constants, avoid 'magic' numbers in code */
...
for (;;) {  /* loop until non-numeric encountered */
    int x;
    if (scanf("%d", &x) != 1)     /* check for non-numeric */
        break;
    if (x < 0 || x >= NMAX) {   /* validate value in range */
        fprintf (stderr, "error: value outside of range -- "
                 "try again.\n");
        continue;      /* if out of range - get new number */
    }
    numarray[x]++;     /* increment frequency at element x */
}

现在,您的情况下0-99与C中使用的基于零的数组索引完全匹配,但是您可以通过调整索引来对任何范围进行索引.例如,如果您对50-150范围感兴趣,则只需根据需要调整索引(例如numarray[x-50]++;)

Now in your case the 0-99 exactly matches the zero-based array indexing used in C, but you can index any range simply by adjusting the indexes. For example, if you were interested in a range of 50-150 you would simply adjust the indexes as required (e.g. numarray[x-50]++;)

但是,在您的代码中,还不清楚您的实际意图是什么.例如,您要求输入0-99之间的值,然后将numarray声明为浮点类型.如果您打算让用户输入整数值,那么您的数组类型应该是 integer 类型.这可以简化为经典的频率问题,您可以通过以下类似的方式简单地对其进行处理:

However, in your code, it is quite unclear what your actual intent is. For instance you ask for values between 0-99, but then declare numarray as a floating-point type. If your intent was to have the user enter whole number values, then your array type should be an integer type instead. That reduces to the classic frequency problem which you could handle simply in a manner similar to the following:

#include <stdio.h>
#include <stdlib.h>

#define NMAX 100  /* define constants, avoid 'magic' numbers in code */

int main (void){

    int i, numarray[NMAX] = {0};  /* C favors all lower-case over
                                   * camelCase variable names  */

    printf ("Enter any number of integers between 0 and 99 "
            "followed a non-numeric: \n");

    for (;;) {  /* loop until non-numeric encountered */
        int x;
        if (scanf("%d", &x) != 1)     /* check for non-numeric */
            break;
        if (x < 0 || x >= NMAX) {   /* validate value in range */
            fprintf (stderr, "error: value outside of range -- "
                    "try again.\n");
            continue;      /* if out of range - get new number */
        }
        numarray[x]++;     /* increment frequency at element x */
    }

    for (i = 0; i < NMAX; i++)   /* output frequency of values */
        printf (" %2d : %d times\n", i, numarray[i]);

    return EXIT_SUCCESS;
}

使用/输出示例

例如,您可以在0-99之间生成500值,并输出生成的每个500数字的频率,这些频率类似于以下内容:

For example, you can generate 500 values between 0-99 and output the frequency for each of the 500 numbers generated with something similar to the following:

$ ./bin/freqarray < <(for i in $(seq 1 500); do
printf " %d" $(($RANDOM %100)); done; echo "done")
Enter any number of integers between 0 and 99 followed a non-numeric:
  0 : 4 times
  1 : 7 times
  2 : 7 times
  3 : 4 times
  4 : 5 times
  5 : 11 times
  6 : 5 times
  7 : 5 times
  8 : 3 times
  9 : 8 times
 10 : 5 times
 ...
 90 : 8 times
 91 : 2 times
 92 : 5 times
 93 : 8 times
 94 : 4 times
 95 : 4 times
 96 : 8 times
 97 : 6 times
 98 : 4 times
 99 : 8 times

处理浮点值

现在,如果您确实希望用户输入浮点数值,例如58.0183158.01826538等...,从概念上讲每个数字的频率没有任何区别,但是考虑到存储浮点数字的方式,实现起来要复杂得多.在记忆中.请参阅 IEEE浮点 和该站点上的大量文章.与浮点存储和随机用户输入的精确比较有关的问题可能很快就会变得相当复杂.即使对于0-99的范围,也确实包含4e+18 + 64位值.

Now if you truly wanted your user to enter floating-point values, e.g. 58.01831, 58.01826538, etc..., conceptually accounting for the frequency of each number isn't any difference, but the implementation is much more involved given the way floating-point numbers are stored in memory. See IEEE floating point and the numerous post on this site. The problems related to floating point storage and exact comparison of random user input can become fairly involved -- quickly. Even for the range of 0-99 there are literally 4e+18+ 64-bit values involved.

如第二条评论中所述,一种有用的方法是哈希输入值并将哈希值存储在哈希表中减小跟踪/存储所有值所需的数组的大小.您必须在保持存储大小与精度之间取得平衡.

As noted in the second comment, one approach that can help is to hash the input values and store the hashed values in a hash-table to reduce the size of the array needed to track/store all values. You will have to balance precision you keep against storage size.

您无法声明4e+18元素的数组. 哈希表本质上提供了存储和查找机制,该机制可以为您提供合理的准确性,还可以提供合理的存储大小.如果用户输入具有相同 hash 的2个值,则会在您的表中生成一个 collision ,您可以使用它来指示重复的条目.如果这是您的意图,那么您将需要研究可用于满足您需求的浮点散列函数(从您的问题来看,这似乎不像您的意图,并且远远超出了此处的全面说明)

There is no way you could declare an array of 4e+18 elements. A hash table essentially provides a storage and lookup mechanism that can give you reasonable accuracy, and also provides a reasonable storage size. If the user enters 2-values that have the same hash a collision will be generated in your table, which you could use to indicate a duplicate entry. If that was your intent, then you will need to investigate the floating point hash functions available to meet your needs (which from your question, doesn't seem like what you intended, and it well beyond full-explanation here)

仔细研究一下,如果您有任何疑问,请告诉我.如果您的意图不同,请编辑问题,我们很乐意与您进一步合作.

Look things over and let me know if you have any questions. If your intent was different, then please edit the question and I'm happy to work with you further.

脚注1:选择一个数组 type ,它可以容纳您期望的最大条目数,例如数组中的每个int元素最多可以捕获INT_MAX2147483647重复(其中int32-bits)

footnote 1: choose an array type capable of holding the maximum number of entries you expect, e.g. each int element of the array can capture a maximum of INT_MAX, or 2147483647 repetitions (where an int is 32-bits)

脚注2:通常,C倾向于所有小写的变量名,并避免使用 camelCase MixedCase 变量名;保留所有大写的常量和宏.这是样式问题-完全取决于您.

footnote 2: C generally favors variable names of all lower-case, and avoids the use of camelCase or MixedCase variable names; reserving all upper-case for constants and macros. It is a matter of style -- so it is completely up to you.

这篇关于如何查找一个数字在数组中重复多少次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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