简体   繁体   English

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

[英]Need function to find largest value in an array, return it to main( ) and print out

To me, my program looks like it should do what I want it to do: prompt a user to enter 10 values for an array, then find the largest of those values in the array using a function, then return the largest number to the main () function and print it out. 对我来说,我的程序看起来应该按照我想要的去做:提示用户为一个数组输入10个值,然后使用一个函数在数组中找到最大的那些值,然后将最大的数返回给主函数。 ()函数并打印出来。

But, when I enter values, I never get numbers back that look anything like the ones I'm entering. 但是,当我输入值时,我再也找不到像我输入的数字那样的数字了。

For example, let's say I enter just "10, 11" I get back "1606416648 = largest value". 例如,假设我只输入“ 10,11”,然后返回“ 1606416648 =最大值”。

Does anyone know what I'm doing wrong? 有人知道我在做什么错吗?

Here's the code: 这是代码:

#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;
}

scanf("%d", &str[LIMIT]); reads in one number and puts it in the memory location one past the end of your array. 读入一个数字,并将其放在数组末尾的内存位置。

After changes: 更改后:

  1. You don't need scanf() in your while condition; 您在while条件中不需要scanf() it should go in the while body instead. 它应该放在while身体中。

  2. Your scanf() still isn't quite right. 您的scanf()仍然不太正确。 You need to tell it where in the array you want to store the input. 你需要告诉在阵列中要存储的输入。

  3. str[i]; doesn't do anything. 什么也没做

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

This doesn't do what you think. 这不符合您的想法。 First, it only reads one number in. Second, you are reading it into the last position + 1 of the array. 首先,它仅读入一个数字。其次,您正在将其读入数组的最后一个位置+1。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM