gpt4 book ai didi

C 计算一个数组中的 int 在另一个数组中出现的频率

转载 作者:行者123 更新时间:2023-11-30 18:51:54 26 4
gpt4 key购买 nike

我正在尝试解决一个练习,要求我首先创建 2 个数组,按升序对它们进行排序,然后计算第一个数组中的数字在第二个数组中出现的次数。我快完成了。一切似乎都工作得很好,除了一行破坏了整个代码。我不明白为什么。我对 C 很陌生,这是我第一次练习这种语言。

这是代码。我已经评论了不起作用的行:

#include <stdio.h>

void sort(int a[]) {
int i, j, l, t;
l = sizeof(a) / sizeof(a[0]);

for (i = 0; i < l + 1; i++) {
for (j = 0; j < (l - i); j++) {
if (a[j] > a[j + 1]) {
t = a[j];
a[j] = a[j + 1];
a[j + 1] = t;
}
}
}
}

void numberOfTimes(int a[], int b[]) {
int al = sizeof(a) / sizeof(a[0]);
int bl = sizeof(b) / sizeof(b[0]);
int i, p, c = 0;

for (i = 0; i <= al; i++) {
for (p = 0; i <= bl; p++) {
if (a[i] == b[p]) {
c++; // <-------- This line doesn't work. Why?
}
}
printf("(%d, %d) ", a[i], c);
}
}

void main() {
int maxarraylen = 1000, i;
int a[maxarraylen];
int b[maxarraylen];
int v, t;

printf("Type elements of A seperated by spaces. Do not enter duplicates (type 'end' to stop): ");
while (scanf("%d", &a[i]) == 1)
i++;
scanf("%*s");
i = 0;

printf("Type elements of B seperated by spaces(type 'end' to stop): ");
while (scanf("%d", &b[i]) == 1)
i++;
scanf("%*s");

sort(a);
sort(b);

numberOfTimes(a, b);
}

这个想法是,代码首先对两个数组进行排序,然后以 (n, m) 格式打印出来。 n 是数组 a 中的 intm 是它在数组 b< 中出现的次数.

例如,您输入:

a = {3, 2 ,1}
b = {1, 3, 2, 3, 3, 2, 1}

代码首先进行排序:

a = {1, 2, 3}
b = {1, 1, 2, 2, 3, 3, 3}

然后打印数组 a 中的数字在 b 中出现的次数:

(1, 2) (2, 2) (3, 3)

最佳答案

您无法根据作为参数接收的指针计算数组大小:l = sizeof(a)/sizeof(a[0]);仅适用于 a是一个数组,而不是一个指针。

您必须将数组大小传递给函数sortnumberOfTimes 。在您的代码中,数组大小不是您需要的,而是为每个数组实际解析的元素数量。您必须专门存储这些数字。

请注意,您的排序代码不正确,不应调整 j的上限以避免访问超出末尾的数组元素。 numberOfTimes 也是如此。功能。计数c必须设置为0对于 a 的每个新元素您在 b 中搜索.

请注意,您的代码没有利用 a 的事实和b已排序。

这是更正后的版本:

#include <stdio.h>

void sort(int a[], int l) {
int i, j, t;

for (i = 0; i < l; i++) {
for (j = 0; j < l - i - 1; j++) {
if (a[j] > a[j + 1]) {
t = a[j];
a[j] = a[j + 1];
a[j + 1] = t;
}
}
}
}

void numberOfTimes(int a[], int al, int b[], int bl) {
int i, p, c;

for (i = 0; i < al; i++) {
c = 0;
for (p = 0; p < bl; p++) {
if (a[i] == b[p]) {
c++; // <-------- This line doesn't work. Why?
}
}
printf("(%d, %d) ", a[i], c);
}
}

int main(void) {
int maxarraylen = 1000, i;
int a[maxarraylen];
int b[maxarraylen];
int al, bl, v, t;

printf("Type elements of A separated by spaces. Do not enter duplicates (type 'end' to stop): ");
for (i = 0; i < maxarraylen; i++) {
if (scanf("%d", &a[i]) != 1)
break;
}
scanf("%*s");
al = i;

printf("Type elements of B separated by spaces(type 'end' to stop): ");
for (i = 0; i < maxarraylen; i++) {
if (scanf("%d", &b[i]) != 1)
break;
}
scanf("%*s");
bl = i;

sort(a, al);
sort(b, bl);

numberOfTimes(a, al, b, bl);
return 0;
}

关于C 计算一个数组中的 int 在另一个数组中出现的频率,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35676963/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com