【问题标题】:Finding Max Number in an Array C Programming在数组 C 编程中查找最大数
【发布时间】:2009-11-06 21:03:42
【问题描述】:

我正在尝试查找数组中的最大数。我创建了一个函数,我正在使用以下代码:

int maxValue( int myArray [], int size)
{
    int i, maxValue;
    maxValue=myArray[0];

    //find the largest no
    for (i=0;i)
        {
        if (myArray[i]>maxValue)
        maxValue=myArray[i];
        }   
        return maxValue;
}

但是,我在 ) 令牌之前收到语法错误。我做错了什么,我什至做对了吗?任何帮助将不胜感激。

【问题讨论】:

标签: c


【解决方案1】:

您必须将一个包含至少一个成员的有效数组传递给此函数:

#include<assert.h>
#include<stdio.h>
#include<stdlib.h>
#include<time.h>

int
maxValue(int myArray[], size_t size) {
    /* enforce the contract */
    assert(myArray && size);
    size_t i;
    int maxValue = myArray[0];

    for (i = 1; i < size; ++i) {
        if ( myArray[i] > maxValue ) {
            maxValue = myArray[i];
        }
    }
    return maxValue;
}

int
main(void) {
    int i;
    int x[] = {1, 2, 3, 4, 5};
    int *y = malloc(10 * sizeof(*y));

    srand(time(NULL));

    for (i = 0; i < 10; ++i) {
        y[i] = rand();
    }

    printf("Max of x is %d\n", maxValue(x, sizeof(x)/sizeof(x[0])));
    printf("Max of y is %d\n", maxValue(y, 10));

    return 0;
}

根据定义,数组的大小不能为负数。 C 中数组大小的适当变量是size_t,使用它。

您的for 循环可以从数组的第二个元素开始,因为您已经使用第一个元素初始化了maxValue

【讨论】:

  • 这太完美了!如果我想在数组中找到最小的数字,我假设我只是做相反的事情?
  • 请注意,这假设您的数组至少有一个元素:gcc.gnu.org/onlinedocs/gcc-4.1.2/gcc/Zero-Length.html
  • 为什么不用 i++ 或 ++i 而不是 i += 1?
  • @Nate Kohl - 这是在 GNU C 中,而不是 ISO/ANSI C(甚至是 C99)。这是一个非标准的扩展,因此思南的代码不需要考虑它。
  • @David - 我知道,但@Nate 说你可以将int Array[0] 变量作为参数传递,这会破坏这段代码,因为这段代码假定(应该)任何数组( /pointer) 传递了至少一个元素。
【解决方案2】:

一个for循环包含三个部分:

for (initializer; should-continue; next-step)

for 循环相当于:

initializer;
while (should-continue)
{
    /* body of the for */
    next-step;
}

所以正确的代码是:

for (i = 0; i < size; ++i)

【讨论】:

  • 你所说的关于这三个部分的信息非常丰富。感谢您的提示!
  • @R Samuel:我会将“应该继续”更改为“终止条件”,因为它就是这样;这是终止循环的条件。
【解决方案3】:

for 后面的括号似乎缺少一些内容。

通常应该是这样的

for (i=0; i<size; i++)

【讨论】:

    【解决方案4】:

    包括:

    void main()
    {
      int a[50], size, v, bigv;
      printf("\nEnter %d elements in to the array: ");
    
      for (v=0; v<10; v++)
        scanf("%d", &a[v]);
    
      bigv = a[0];
    
      for (v=1; v<10; v++)
      {
        if(bigv < a[v])
          bigv = a[v];
      }
    
      printf("\nBiggest: %d", bigv);
      getch();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-05-25
      • 2021-07-28
      • 2017-08-18
      • 2021-11-29
      • 2021-06-20
      • 2013-11-28
      相关资源
      最近更新 更多