我正在尝试编写一个程序来获取最大值,但它无法正常工作。计算在名为max_number
的函数内执行。
错误是什么?
#include <stdio.h>
int max_number(int storeX[], int i)
{
int max=0,x;
for(x=0;x<i;x++)
{
if(storeX[x]<max)
{
max = storeX[x];
}
return max;
}
return 0;
}
int main()
{
int i,x,numbers,max;
printf("how many numbers do you want to compare?\n");
scanf("%d",&i);
int storeX[i];
for(x=0;x<i;x++)
{
printf("the %d number is:",x+1);
scanf("%d",&numbers);
numbers=storeX[x];
}
max=max_number(storeX,i);
printf("the max number is: %d",max);
return 0;
}
答案 0 :(得分:0)
代码中存在一些问题,已对代码进行了更改以使其正常工作。检查代码中的注释以了解。
#include <stdio.h>
#include <limits.h>
int max_number(int storeX[], int i)
{
int max=INT_MIN,x; //In case you array has all negative numbers
for(x=0;x<i;x++)
{
if(storeX[x]>max) // This if condition is wrong
{
max = storeX[x];
}
//return max; // You need to iterate the whole array
}
return max;
}
int main()
{
int i,x,numbers,max;
printf("how many numbers do you want to compare?\n");
scanf("%d",&i);
int storeX[i];
for(x=0;x<i;x++)
{
printf("the %d number is:",x+1);
scanf("%d",&storeX[x]); // Need to pass a reference to the array index
//numbers=storeX[x]; //dosen't assign the value to storeX[x] instead the otherway around
}
max=max_number(storeX,i);
printf("the max number is: %d\n",max);
return 0;
}