我一直在尝试开发一个控制台程序来对数组进行排序,然后允许用户在数组中搜索特定值。在大多数情况下,排序部分工作正常(尽管我想将其简化为一个 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/