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

标签 c++ function output

除了一个小问题外,这段代码对我来说工作得很好。在调用我的 find_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;

}

最佳答案

在这两行中:

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

你正在使用 std::cout 来打印这些函数的返回值(int),但是在你的函数定义中你没有返回任何值,所以它会打印一个垃圾值.

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

关于C++函数在endl(内存变量?)之后打印不需要的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47119875/

相关文章:

c++ - 无法在线程中专门化函数模板

c++ - 如何将深拷贝构造函数实现到链表中?

R:将数据框返回到工作区,并从函数参数中命名

mysql - 我没有得到以下 sql 批处理文件的输出文件

layout - 在 Lisp 中打印列中的嵌套列表

ios - 返回错误的结果用于在 swift 中打印 FIRST 和 LAST DATE OF THE MONTH

c++ - 如何在设计层面移除 dynamic_cast

c++ - 为什么 auto 不能用于重载函数?

c - 在传递给函数的数组上使用 sizeof()

Python代码对象、函数和默认参数