getHighest 函数调用在产生 0 的C++会导致错误

getHighest function call in C++ producing 0 results in error

本文关键字:C++ 错误 函数调用 getHighest      更新时间:2023-10-16

这是下面的代码。 当我执行代码时,getLowest 工作正常,因为它返回 13,这是正确的。但是,getHighest 返回 0 时它应该是 40。屏幕上的返回为 0,而它应该是 40。那里有什么我可以改变的。我已经给出了 4 个 int 类型,除了 getHighest 函数之外,调用正在正常执行。

#include "stdafx.h"
#include <iostream>
using namespace std; 
//function prototype 
int getHighest(int numArray[], int numElements); 
int getLowest(int numArray[], int numElements);

int main()
{
    int numbers[4] = { 13, 2, 40, 25 };
    cout << "The highest number in the array is "
        << getHighest(numbers, 2) << "." << endl;
    cout << "The lowest number in the array is "
        << getLowest(numbers, 1) << "." << endl;

    system("Pause");
    return 0;

} // end of main function 
//******function definitions******
int getHighest(int numArray[], int numElements);
int getHighest(int numArray[], int numElements)
{
    return 0;
}
int getLowest(int numArray[], int numElements)
{
    //assign first elemet's value to the high variable
    int high = numArray[0];
    int low = numArray[0];
    //begin search with second element
    for (int sub = 1; sub < numElements; sub += 3)
        if (numArray[sub] > high)
            high = numArray[sub];
    for (int sub = 1; sub < numElements; sub += 1)
    if (numArray[sub] > low)
        low = numArray[sub];
    //end if 
    //end for
    return low; 
    return high;

 //end of getHighest function
    return 0;
}

在getMinimum函数中,你返回low,当你执行返回指令时,它会返回值并退出它正在执行的任何操作。在getMinimum中,你直接返回一个0,你并没有在那里做任何事情,我会建议修复你的代码:

     int getLowest(int numArray[])
        {
            //int high = numArray[0]; in this function let´s just search for the lowest
            int numElements = sizeof( numArray ) / sizeof( numArray[0] ); //This will count automatically the number of elements in your array
            int low = numArray[0];

            for (int sub = 1; sub < numElements; sub += 1)
            {
              if (numArray[sub] < low)
              low = numArray[sub];
            }
            return low; 
        }

.

  int getHighest(int numArray[])
        {
            int high = numArray[0]; 
            int numElements = sizeof( numArray ) / sizeof( numArray[0] );//This will count automatically the number of elements in your array
            for (int sub = 1; sub < numElements; sub += 1)
            {
                if (numArray[sub] > high)
                high= numArray[sub];
            }
            return high; 
        }

因此,要打电话给他们,您只需要这样做

cout << "The highest number in the array is "
        << getHighest(numbers) << "." << endl;
    cout << "The lowest number in the array is "
        << getLowest(numbers) << "." << endl;