首页 > 解决方案 > 我的程序只输出 1 的最高元素

问题描述

这是我的代码:

using namespace std;

// Function prototypes
int highestElement(int [], int);
void doubleArray(int [], int);
void showValues(int [], int);

int main()
{

   const int ARRAY_SIZE = 7;
   int set[ARRAY_SIZE] = {1, 2, 3, 4, 5, 6, 7};

   // Display the initial values.
   cout << "The arrays values are:\n";
   showValues(set, ARRAY_SIZE);

   // Double the values in the array.
   doubleArray(set, ARRAY_SIZE);

   // Display the resulting values.
   cout << "After calling doubleArray the values are:\n";
   showValues(set, ARRAY_SIZE);


   cout << "The highest element in the array is " << highestElement << endl;

   return 0;
}

//*****************************************************
// Definition of function doubleArray                 *
// This function doubles the value of each element    *
// in the array passed into nums. The value passed    *
// into size is the number of elements in the array.  *
//*****************************************************

void doubleArray(int nums[], int size)
{
   for (int index = 0; index < size; index++)
      nums[index] *= 2;
}

//**************************************************
// Definition of function showValues.              *
// This function accepts an array of integers and  *
// the array's size as its arguments. The contents *
// of the array are displayed.                     * 
//**************************************************

void showValues(int nums[], int size)
{
   for (int index = 0; index < size; index++)
      cout << nums[index] << " ";
   cout << endl;
}

// Definition of highestElement (what I need help fixing)

int highestElement(int numbers [], int size)
{
   int count;
   int highest;
   highest = numbers[0];
   for (count = 1; count < size; count++)
   {
      if (numbers[count] < highest)
      {
      highest = numbers[count];
      }
   }
}

我的错误:

main.cpp:29:54: warning: the address of ‘int highestElement(int*, int)’ will always evaluate as ‘true’ [-Waddress]
    cout << "The highest element in the array is " << highestElement << endl;
                                                      ^~~~~~~~~~~~~~
main.cpp: In function ‘int highestElement(int*, int)’:
main.cpp:75:1: warning: no return statement in function returning non-void [-Wreturn-type]
 }
 ^

我的输出是:

The arrays values are:
1 2 3 4 5 6 7 
After calling doubleArray the values are:
2 4 6 8 10 12 14 
The highest element in the array is 1

问题是无论我做什么,highestElement 总是等于 1。我知道我做错了什么,但我自己无法解决它。我正在尝试输出数组的最高元素。我真诚地等待一个有用的答复。

标签: c++arrays

解决方案


首先,您需要传递为函数声明的参数highestElement

cout << "The highest element in the array is " << highestElement(set, ARRAY_SIZE) << endl;

其次,由于您正在寻找数组中的最大值,您需要检查当前元素是否greater比旧元素:

if (numbers[count] > highest)
{
  highest = numbers[count];
}

第三,你需要return highest从函数highestElement()到主调用者。

return highest;

推荐阅读