C++求N个数中的最大值

#include<stdio.h>
#include<stdlib.h>
int max=0,min=0,d;

main()
{ int Sr(int n);
int s,n;
printf("请输入要比较的数字的个数:");
scanf("%d",&n);
s=n;
d=n+1;
max=Sr(n);
printf("%d个数中最大的是%d\n",s,max);
system("pause");
return 0;
}
int Sr(int n)
{

while(n>0)
{
printf("请输入第%d个数字:",d-n);
scanf("%d",&max);
max=max>min?max:min;
min=max;
Sr(n-1);
}

return min;
}

一、算法思想

假设N个数存储在一维数组中,令第一个数为最大值,从第二个数开始逐个和当前最大值进行比较,若比当前最大值大,则用它替换当前最大值。最后保存的最大值即为N个数中的最大值。


二、操作过程

        49    38    65    97    76    13    27    49            max = 49
               ^
        49    38    65    97    76    13    27    49            max = 65
                     ^
        49    38    65    97    76    13    27    49            max = 97
                           ^
        49    38    65    97    76    13    27    49            max = 97
                                 ^
        49    38    65    97    76    13    27    49            max = 97
                                       ^
        49    38    65    97    76    13    27    49            max = 97
                                             ^
        49    38    65    97    76    13    27    49            max = 97
                                                   ^
        max = 97


三、程序代码

#include <iostream>

using namespace std; 

//返回数组中元素的最大值
//arr:数组
//n:数组大小
//返回n个数组元素的最大值
int max(int arr[], int n)
{
int maxValue = arr[0];

for(int i=1; i<n; i++)
{
if(arr[i] > maxValue)
{
maxValue = arr[i];
}
}

return maxValue;
}

int main() 
{
int arr[] = {49, 38, 65, 97, 76, 13, 27, 49};
int n = 8;

cout<<"最大值:"<<max(arr, n)<<endl;

return 0;
}


四、运行测试

温馨提示:答案为网友推荐,仅供参考
第1个回答  2012-11-15
1)将while(n>0)改成if(n>0)即可正常运行;不过处理负数仍然不行。
2)再将min=0改成min=-INT_MAX,并在前面增加#include <limits.h>,这样就可以输入负数了。本回答被提问者采纳
第2个回答  2016-12-19
#include
#include
void main()
{
int x,n,max;
cout
}

第3个回答  2019-09-16
#include<iostream>
#include<algorithm>
using namespace std;
int n,x[100009];
int main(){
cin>>n;
for(int i=1;i<=n;i++) cin>>x[i];
cout<<*max_element(x+1,x+n+1);
return 0;
}
第4个回答  2019-12-12
max()就行
相似回答