【问题标题】:Comparing arrays in a function比较函数中的数组
【发布时间】:2016-02-27 11:59:17
【问题描述】:

我的函数countCopies 无法正常工作,即使它获得了正确的输入。它所要做的就是将一个整数数组作为输入,然后在这个数组中搜索第二个输入 x 的重复项。

int main() {
    char intArray[100]; //The integer array can only hold 100 integers
    int i, x, j;
    printf("Please enter a couple of integers and when you're done enter end. ");

    i = 0;
    while (scanf("%d", &intArray[i++]) == 1)
        /*empty loop*/;

    scanf("%*s");

    printf("Enter x:");
    scanf("%d", &x);

    printf("Copies = %d\n", countCopies(intArray, i, x));
}

int countCopies(int a[], int n, int x) {
    int count = 0;
    int j = 0;
    for (j = 0; j < n - 1; j++) {
        if (a[j] == x) {
            count++;
        }
    }
    return count;
}

【问题讨论】:

  • j &lt; n - 1 更改为j &lt; n
  • 为什么是scanf("%*s"); ??
  • @AshishAhuja 我知道这意味着什么,但我很困惑为什么在这里使用它(我看不出有任何理由在这里使用它。
  • @ameyCU:看我的回答:scanf("%*s"); 跳过了end 字。与往常一样,不明显的代码应该被注释掉。

标签: c


【解决方案1】:

for 循环不正确:您应该将测试更改为j &lt; n。 C 中惯用的 for 循环:for (j = 0; j &lt; n; j++) ... 精确迭代 n 次,j 取值 0n-1 包括在内,这些值恰好对应于 n 元素数组中的所有有效位置。

请注意,数组的元素类型错误:它应该是int,而不是char。您还应该检查第一个循环中的数组边界以及最后一个scanf 的转换是否成功。

这是一个更正的版本:

#include <stdio.h>

int countCopies(int a[], int n, int x);

int main(void) {
    int intArray[100]; //The integer array can only hold 100 integers
    int i, x;

    printf("Please enter a series of integers, end the list with the word end.\n");

    for (i = 0; i < sizeof(intArray) / sizeof(*intArray); i++) {
        if (scanf("%d", &intArray[i]) != 1)
            break;
    }
    if (scanf("%d", &x) == 1) {
        printf("too many numbers\n");
        return 1;
    }
    scanf("%*s");  /* skip the end word.  Note that any word is OK */

    printf("Enter x:");
    if (scanf("%d", &x) == 1) {
        printf("Copies = %d\n", countCopies(intArray, i, x));
    }
    return 0;
}

int countCopies(int a[], int n, int x) {
    int j, count = 0;

    for (j = 0; j < n; j++) {
        if (a[j] == x) {
            count++;
        }
    }
    return count;
}

【讨论】:

  • 我建议在for循环之前计算元素的数量,而不是在每次迭代中计算。
  • @chqrlie,请在发布之前测试您的代码。它不起作用。我同意 OP 犯了这个错误,但仍然将其作为正确的代码提及是错误的。
  • @ameyCU: 好点,条件应该尽可能快地求值,但在这种情况下,sizeof 表达式是一个编译时间常数,在条件表达式中使用它没有开销.
  • 感谢您这么快回复,确实是个愚蠢的错误。
【解决方案2】:

要扩展 chqrlie 的答案,

代码for (i = 0; i &lt; n; i++) {/* do stuff */}按以下顺序执行:

  1. 变量i 设置为零。
  2. 条件 i /* do stuff */中的代码,否则,退出循环。
  3. 应用了增量i++
  4. 回到 2。

这意味着在循环迭代中,当 i 递增到 n 时,for 循环会在循环内的代码执行之前中断,因此,如果您正在访问具有 n 个元素的数组,则最后一个被访问的元素具有索引 n - 1。因此 chqrlie 提到了 C 循环范式。

【讨论】:

    猜你喜欢
    • 2022-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-24
    • 1970-01-01
    • 2019-10-14
    • 1970-01-01
    相关资源
    最近更新 更多