简体   繁体   中英

Function returning the wrong value

This project is a homework assignment for school. The instructor has asked us to input 20 random integers then print the smallest in the list and then search the list for the first iteration of the number entered. My problem is returning the smallest number of the list. The function, shown below accepts an integer array and an integer with the size of the array. In Visual Studio, the tests for the smallest number work until the function returns the value. Instead of returning the smallest number, the function returns some kind of default value as opposed to the smallest integer. I have been staring at this code for the past two hours, any help would be appreciated.

int theSmallest(const int a[], int number_used)
{
    int temp = a[0];
    // Find the smallest number in array a[]
    for (int i = 0; i <= number_used; i++)
    {
        if (temp >= a[i])
        {
            temp = a[i];
        }
    }
    return temp;
}

Your program has undefined behavior because you are accessing the array a using an invalid index.

When an array has 20 elements, the valid indices are 0-19, not 0-20.

You are using

for (int i = 0; i <= number_used; i++)

and then accessing a[i] in the loop. If number_used is equal to 20, you are accessing a using and index value of 20, which is not correct.

Change that to use i < number_used .

for (int i = 0; i < number_used; i++)

A minor issue is that you are using temp >= a[i] , which can be changed to use temp > a[i] . Use of >= in this case will work but it will do more work than necessary.


Here's an updated version of the function:

int theSmallest(const int a[], int number_used)
{
    int temp = a[0];
    // Find the smallest number in array a[]
    for (int i = 1; i < number_used; i++)
    {
        if (temp > a[i])
        {
            temp = a[i];
        }
    }
    return temp;
}

Assuming number_used is the size of array, code can be written as:

int theSmallest(const int a[], int number_used)
{
    if( a == nullptr or number_used == 0 )
        throw std::runtime_error( "invalid argument" );
    return *std::min_element( a, a + number_used );
}

Note: you code has issue in case number_used is equal to 0 or a pointer is passed as nullptr , you may not expect that to happen but it is good idea to always validate your input (at least by assert())

Change to i < number_used and I think change to if(temp > a[i]) .

You can also start i=1 since you made the assumption index 0 is the smallest.

Change

for (int i = 0; i <= number_used; i++)

to

for (int i = 1; i < number_used; i++)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM