【发布时间】:2017-03-13 23:56:12
【问题描述】:
我一直在尝试开发一个对数组进行排序的控制台程序,然后允许用户在数组中搜索特定值。在大多数情况下,排序部分工作正常(虽然我想将其简化为一个 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;
}
【问题讨论】:
-
for( i = 0; i<=num ; ++i)应该是for( i = 0; i<num ; ++i)。否则你的数组太短了。 -
顺便说一句,您的问题还不错,但也不是很好。查看代码的格式:太多的空行和损坏的缩进。难以阅读。幸运的是,您已将错误放在第一行 :)
-
旁白:
scanf(" %d ",&user_array[i]);这样的行是错误的,请删除空格,尤其是尾随的会影响后续输入。前面的那些根本是不必要的(使用%c格式时可能只有一个)。scanf("%d", &user_array[i]); -
奇怪数字的原因在这里:
printf(" %d",&truth);打印的是truth的地址,而不是truth的值。删除&以获取值。 -
@Jean-François Fabre 好的,所以我进行了更正,但我仍然收到 6487516 号,您认为它指向内存位置吗?