我想获取数组中最大数字的索引,但是我一直保持索引零! [英] I want to get the index of largest number in array but I keep getting index zero !!!!!!

查看:119
本文介绍了我想获取数组中最大数字的索引,但是我一直保持索引零!的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在执行一个函数,该函数返回数组中最大数字的索引;这是一个简单的函数,但是我不知道为什么我会被代码卡住.无论输入什么数字它返回索引号0,尽管最大的数字可能例如在索引号6或7中.这是我的代码:

I''m doing a function that returns the index of the largest number in the array ;it''s an easy function but I don''t know why I''m getting stuck with code.whatever numbers I enter it returns an index number 0 although the largest number maybe in index number 6 or 7 for example.this is my code:

int MAX_INT(int arr[],int s)
{
  int Max,temp;
  int i=0;
  temp=i;
  Max=arr[i];
  while(i<s)
  {
      if(Max>arr[i+1])
      {
          Max=arr[0];
          temp=0;
      }


      else{
          Max=arr[i+1];
          temp=i;
      }
     i++;
  }
  return temp;
}
int main()
{
  int arr[SIZE];
	for(int i=0;i<SIZE;i++)
	
		cin>>arr[i];
	
	cout<<MAX_INT(arr,SIZE);
}


谢谢
:)


Thank you
:)

推荐答案

更改您的if语句;

Change your if statement ;

int MAX_INT(int arr[],int s)
{
    int Max,temp;
    int i=0;
    temp=i;
    Max=arr[i];
    while(i<s)>
    {
        if (Max < arr[i])
        {
            Max=arr[i];
            temp=i;
        }
        i++;
    }
    return temp;
}


更快,更安全,更简单:
Quicker, safer, simpler:
#include <algorithm>
int MAX_INT(int arr[],int s)
{
    return std::max_element(arr, arr + s) - arr;
}


欢呼声,
AR
编辑以返回索引.


cheers,
AR
Edited to return index.


请谨慎使用索引:
Ba careful with your index:
int MAX_INT(int arr[],int s)
{
  int i=0;
  Max=arr[i];
  while(i<s)
  {
      //what will happen if i equals s - 1 ???
      if(Max>arr[i+1])
      {
          //...
      }
      i++;
   }
}



我建议这样做:



I suggest this:

int MAX_INT(int arr[], int s)
{
   if (s <= 0)
      return -1;
   int maxIndex = 0;
   int maxValue = arr[0];
   for (int i = 1; i < s; i++)
   {
      if (arr[i] > maxValue)
      {
          maxValue = arr[i];
          maxIndex = i;
      }
   }
   return maxIndex;
}


这篇关于我想获取数组中最大数字的索引,但是我一直保持索引零!的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆