我应该从现有数组中创建新数组(例如 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/