需要函数来查找数组中的最大值,将其返回到main()并打印输出

时间:2013-03-12 01:33:09

标签: c

对我来说,我的程序看起来应该做我想做的事情:提示用户为数组输入10个值,然后使用函数找到数组中最大值,然后返回最大数字到main()函数并打印出来。

但是,当我输入数值时,我从来没有得到数字,看起来就像我正在进入的数字。

例如,假设我只输入“10,11”,我回来“1606416648 =最大值”。

有谁知道我做错了什么?

以下是代码:

#include <stdio.h>
#define LIMIT 10
int largest(int pointer[]); 
int main(void)
{

int str[LIMIT];
int max;
int i = 0;

printf("Please enter 10 integer values:\n");
while (i < LIMIT)
{
    scanf("%d", &str[i]);
    i++;
}
// Thanks for your help, I've been able to make the program work with the above edit!
max = largest(str);
printf("%d = largest value\n", max);

return 0;
}

int largest(int pointer[])

{
int i;
int max = pointer[0];

for (i = 1; i < LIMIT; i++)
{
   if (max < pointer[i])
        max = pointer[i];
}
return max;
}

2 个答案:

答案 0 :(得分:1)

scanf("%d", &str[LIMIT]);读入一个数字并将其放在数组末尾的内存位置。

更改后:

  1. 您在while条件下不需要scanf();它应该进入while身体。

  2. 您的scanf()仍然不太对劲。你需要告诉它想要存储输入的数组中的 where

  3. str[i];没有做任何事情。

答案 1 :(得分:0)

printf("Please enter 10 integer values:\n"); scanf("%d", &str[LIMIT]);

这不符合你的想法。首先,它只读取一个数字。其次,你将它读入数组的最后一个位置+ 1。