C程序搜索一个数字并计算它在数组中的出现次数

C program to search for a number and count its occurrences in an array

此代码工作方式有误,我正在寻找解决方案,但无法应用。我想分隔 for 循环外但在 if 语句内的一行代码,因为知道 if 语句在嵌套循环内。

我的意思是这一行:printf("\n fianl result %d has appeard %d in the array", j, count);

int main() {
    int array[10];
    int i, j;
    int count = 0;

    printf("Enter numbers\n");
    for (i = 0; i <= 9; i++) {
        scanf("%d", &array[i]);
    }

    printf("Enter the number you are looking for:\n");
    scanf("%d", &j);
    for (i = 0; i <= 9; i++) {
        if (j == array[i]) {
            printf("%d is in the array it is in entery %d\n", j, i+1);
            count++;
            printf("\n fianl result %d has appeard %d in the array", j, count);
            printf("Enter another number \n");
            scanf("%d", &j);
        } else {
            printf("%d is not the array", j);
            printf("Enter another number");
            scanf("%d", &j);
        }
    }
    return 0;
}

您应该将 scanfs 移出 for 循环,这样它们就不会在您扫描数组时执行。输入 -1 结束 while 循环。

// your variables and array setup goes here
...
printf("Enter the number you are looking for:\n");
scanf("%d", &j);
while (j != -1) {
    int count = 0;
    for (i = 0; i <= 9; i++) {
        if (j == array[i]) {
            printf("%d is in the array it is in entery %d\n", j, i+1);
            count++;
        }
    }
    if (count == 0) {
        printf("%d is not the array", j);
    } else {
        printf("\n final result %d has appeared %d times in the array", j, count);
    }

    printf("Enter the number you are looking for:\n");
    scanf("%d", &j);
}