C++ 求数组中最大值

来源:互联网 发布:tensorflow中文教程 编辑:程序博客网 时间:2024/05/21 05:38

 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
*/

 

原创粉丝点击