c - 如何通过计算值出现的次数并将其打印在该值旁边来创建一个新数组?

标签 c arrays find-occurrences

我应该从现有数组中创建新数组(例如 1 0 4 5 4 3 1),以便新数组包含现有数组中已有的数字及其出现的次数。 因此,新的看起来像这样: 1 2 0 1 4 2 5 1 3 1 (1 出现 2 次,0 出现 1 次...3 出现 1 次;它们在第一个数组中出现的顺序应该是也保留在新的中);我知道怎么数数。一个值在数组中出现的次数,但如何插入出现的次数? (C语言)

 #include <stdio.h>
    #define max 100
    int main() {


int b, n, s, i, a[max], j, k;

printf("Enter the number of array elements:\n");
scanf("%d", &n);

if ((n > max) || (n <= 0)) exit();

printf("Enter the array:\n");
for (i = 0; i < n; i++)
    scanf("%d", a[i]);

for (i = 0; i < n; i++) {
    for (j = i + 1; j < n;) {
            if (a[j] == a[i]) {
                for (k = j; k < n; k++) {
                    a[k] = a[k + 1];
}}}}

    //in the last 5 rows i've tried to compare elements, and if they are same, to increment the counter, and I've stopped here since I realised I don't know how to do that for every digit/integer that appears in array//

最佳答案

如果您知道现有数组由 0 到 9 之间的数字组成,则可以使用数组的索引来指示要递增的值。

int in[12]  = {1,5,2,5,6,5,3,2,1,5,6,3};
int out[10] = {0,0,0,0,0,0,0,0,0,0};

for (int i = 0; i < 12; ++i)
{
  ++out[ in[i] ];
}

关于c - 如何通过计算值出现的次数并将其打印在该值旁边来创建一个新数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44226256/

相关文章:

c - 这两个指向 char 初始化的指针之间的区别

java - 循环遍历 arrayList

count - 在 L. LISP 的任何地方发现符号 A 的出现

c# - 解决异常 "out of range"错误行为

c - 在函数内部初始化后,将值赋给字符数组的元素时出错

C 编程初学者 - 请解释这个错误

c - 警告 : unknown escape sequence '\

javascript - 在 JavaScript 中根据子值从 n 维数组中选择一个值

用 C 中的函数更改数组?

python - 使用 panda 查找表列中的匹配项