C++ 求数组中最大值

 Max value

//============================================= max
// From algorithms/arrayfuncs.cpp
// Returns the maximum value in an array.
float max(float a[], int size) {
    assert(size > 0);        // Note 1.
    float maxVal = a[0];     // Note 2.
    for (int i=1; i<size; i++) {
        if (a[i] > maxVal) {
            maxVal = a[i];
        }
    }
    return maxVal;
}//end max

Notes:

    Computing the maximum requires there is at least one value in the array. The "assert" enforces this requirement.
    The initial value for the maximum starts at the value of the first element instead of zero. Zero is commonly used, but doesn't work when all array elements are negative!

Max index
Another approach to the maximum is to return the index of the maximum value instead of the value. This is an advantage when the values are large or contain dynamically allocated values that makes assignment a non-trivial operation. Another reason to return the index is so that the value at that location in the array can be changed.


//============================================= maxIndex
// From algorithms/arrayfuncs.cpp
// Returns the index of the maximum value in an array.
int maxIndex(float a[], int size) {
    assert(size > 0);
    int maxIndex = 0;
    for (int i=1; i<size; i++) {
        if (a[i] > a[maxIndex]) {
            maxIndex = i;
        }
    }
    return maxIndex;
}//end maxIndex

Extracted from algorithms/arrayfuncs.cpp

-------------------------------

-------------------------------

代码:#include <iostream>
using namespace std;
class Array_max
{
public:
 void set_value();
 void max_value();
 void show_value();
private:
 int array[10];
 int max;
};
void Array_max::set_value()
{
 int i;
 for(i=0;i<10;i++)
  cin>>array[i];
}
void Array_max::max_value()
{
 int i;
 max=array[0];
 for(i=1;i<10;i++)
  if(array[i]>max) max=array[i];
}
void Array_max::show_value()
{cout<<"max="<<max;}

int main()
{
Array_max arrmax;
arrmax.set_value();
arrmax.max_value();
arrmax.show_value();
return 0;
}

----------------------------------------------------

---------------------------------------------------------

//C++ 指针的方式找出一维数组中的最大值和最小值
#include<iostream>
using namespace std;

void main()
{
 int c[]={1,4,0,2,5,3};
 int size_c=sizeof(c)/4;
 int max=*c;
 int min=*c;

 int i;
 int temp;
 for(i=1;i<size_c;++i)
 {
  temp=*(c+i);
  if(temp>max)
   max=temp;
  if(temp<min)
   min=temp;
 }
 cout<<"max="<<max<<endl
  <<"min="<<min<<endl;
}

/*
max=5
min=0
Press any key to continue
*/

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值