C++ 函数在 endl 之后打印不需要的数字(内存变量?)

Wah*_*cht 2 c++ function output

除了一个小问题之外,这段代码对我来说工作得很好。在调用 myfind_minfind_max函数之后,代码还打印出一个看似随机的数字。我认为这与引用传递有关,它是一个内存值或其他东西。有人可以解释并告诉我如何摆脱它吗?谢谢。

#include <iostream>
#include <fstream>
#include <cmath>
#include <cstdlib>

using namespace std;

//get_avg function will get the average of all temperatures in the array by using for loop to add the numbers

double get_avg(int* arr, int n) {
    double res = 0.0;
    for(int i = 0; i<n; i++){
        res += arr[i];

    }
    return (res/n); //average
}

void get_array(int* arr){
    int i;

    for(i=0; i<25; i++){
        arr[i] = (rand() % 100) + 1;
    }
}

//prints the results of get_avg in and get_array in table format, then finds difference between avg and temp.

void print_output(int* arr) {
    double avg = get_avg(arr, 24);
    cout << "The average is: " << avg << endl;
    cout << "Position\tValue\t\tDifference from average\n\n";
    char sign;
    for(int i = 0; i < 24; i++){
        sign = (avg > arr[i])?('+'):('-');
        cout << i << "\t\t" << arr[i] << "\t\t" << sign << fabs(avg-arr[i]) << endl;
    }
}

//finds the minimum function using a for loop

int find_min(int* arr, int n) {
    int low = arr[0];
    int index = 0;
    for(int i = 1; i<n; i++){
        if(arr[i] < low){
            low = arr[i];
            index = i;

        }
    }
    cout << "The position of the minimum number in the array is "<< index <<" and the value is " << low << endl;    
}

//finds the maximum function using a for loop

int find_max(int* arr, int n){
    int hi = arr[0];
    int index;
    for(int i = 1; i<n; i++) {
        if(arr[i] > hi) {
            hi = arr[i];
            index = i;
        }
    }
    cout << "The position of the maximum number in the array is "<< index <<" and the value is " << hi << endl;
}



int main(){

    int arr[24]; //declares array


    get_array(arr);
    print_output(arr);
    cout << find_min(arr, 24) << endl; 
    cout << find_max(arr, 24) << endl;

    cout << endl;


    // wrap-up

    cout << "This program is coded by Troy Wilms" << endl;  // fill in your name

    // stops the program to view the output until you type any character

    return 0;

}
Run Code Online (Sandbox Code Playgroud)

HMD*_*HMD 5

在这两行中:

cout << find_min(arr, 24) << endl; 
cout << find_max(arr, 24) << endl;
Run Code Online (Sandbox Code Playgroud)

您正在用来std::cout打印这些函数的返回值(即 int),但在您的函数定义中您没有返回任何值,因此它将打印一个垃圾值。

在函数末尾(find_minfind_max)添加return arr[index];