C 尝试在数组中搜索特定数字

标签 c arrays sorting search

我一直在尝试开发一个控制台程序来对数组进行排序,然后允许用户在数组中搜索特定值。在大多数情况下,排序部分工作正常(尽管我想将其简化为一个 for 循环,但现在必须这样做)。

但是,无论我输入什么数字,搜索部分每次都会给我数字 6487516。我确信这与我的函数 find_number 有关,我只是不知道是什么。

#include <stdio.h>
#include <stdlib.h>
#define NOT_FOUND -1
#define num 9

int main(int argc, char *argv[])
{
    int ask,how_many;
    int user_array[num];
    int sorted_array[num];
    int i,temp,junction;

    printf("type 10 numbers with spaces in between then press enter \n, type the numbers again then press enter, after this press q and then press  enter      ");

    for (i = 0; i<=num ; ++i)
        scanf("    %d      ",&user_array[i]);
    //printf("type ");
    for (i = 0; i<=num ; ++i)
        scanf("    %d      ",&sorted_array[i]);

    for (i = 0; i<=num ; ++i)
        printf("    A : %d  ",user_array[i]);

    for (i = 0; i<=num ; ++i)
        printf("    B : %d  ",sorted_array[i]);

    for (i = 0; i <= num; ++i)
    {
        for (junction = 0; junction <= num - i; junction++)
        {
            if (sorted_array[junction] > sorted_array[junction+1] )
            {
                temp = sorted_array[junction];
                sorted_array[junction] = sorted_array[junction+1];
                sorted_array[junction +1] = temp;
            }
        }
    }

    printf (" Left is the Sorted right is the Original");
    for (i = 0; i<= num; ++i)
        printf(" \n %d,         %d   ",sorted_array[i],user_array[i]);

    printf (" What number do you want to search for?\n");
    fflush (stdin);
    scanf (" %d",&ask);
    printf (" how many numbers? \n");
    fflush (stdin);
    scanf (" %d",&how_many);
    int truth = find_number (sorted_array, ask, how_many);
    printf (" %d",&truth);
    return 0;
}

int find_number( const int target[10], int goal, int n)
{
    int z,found = 0,locate;
    int i = 0;
    while (!found && i < n)
    {
        if (target[i] == goal)
            found = 1;
        else        
            ++i;
    }
    if (found)
        locate = i;
    else
        locate = NOT_FOUND;
    return locate;
}

最佳答案

这是 C 语言中的惯用语:

#define N   20
int array [N];
for (int j=0;  j < N;  ++j)
     //do something with array[j]

请注意,它不是 j <= N 。这会导致访问分配的数组元素,即 array[N] .

关于C 尝试在数组中搜索特定数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40349993/

相关文章:

python - 使用 numpy 数组和元组保持每个元素出现一次的快速方法

c - 在C中交换二维数组(指针到指针)

java - 如何合并N排序两个文本文件

c# 按联系人状态和名称对列表中的对象进行排序

c - pthread_create 的正确参数是什么

c - 将两个别名传递给 `typedef struct` 意味着什么?

克隆 Eclipse 工作区的 Mercurial 存储库并在另一个位置重建

c - 在 Windows 上通过 c 程序执行命令

java - 编写 Yahtzee 程序时遇到问题

java - 同时对多个数组进行排序 "in place"