gpt4 book ai didi

c - 查找数组中的最大数 C 编程

转载 作者:行者123 更新时间:2023-11-30 18:16:39 25 4
gpt4 key购买 nike

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

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

但是我在 ) 标记之前遇到语法错误。我做错了什么,我这样做对吗?任何帮助将不胜感激。

最佳答案

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

#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

关于c - 查找数组中的最大数 C 编程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1690428/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com