繁体   English   中英

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

[英]C++ Function is printing unwanted numbers after endl (memory variable?)

除了一个小问题,这段代码对我来说是完美的。 调用我的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];

正如在另一个答案中已经指出的那样,问题在于没有从声明要返回一个值的函数中返回值。 因此,这里解决方案的很大一部分是阅读和理解编译器的警告!

更好的是,将编译器警告转化为错误(例如,通过使用-Werror选项,对于GNU g ++)。

其他评论建议使用“真实的” C ++类型,例如std::vector作为“数组”的容器,而不是使用C样式的整数数组,并且在迭代集合时使用一些魔术常数。 这都是正确的,甚至可以更进一步:充分了解C ++标准库并使用它! 当这些函数已经可用时,为什么要对这些函数进行编程以获取集合的最小值和最大值?

尝试避免这些陷阱并提供更像C ++的版本,请参见以下示例:

#include <algorithm>
#include <ctime>
#include <ios>  // I/O manipulators
#include <iostream>
#include <numeric>
#include <vector>

using namespace std;

using Container = std::vector<int>;

// get_avg function will get the average of all temperatures in the container
double get_avg(const Container& c) {
    // force promotion from int to double by using 0.0 as initial value!
    return std::accumulate(c.begin(), c.end(), 0.0) / c.size();
}


// fill container c with 'count' random values, originally get_array()
void fill(size_t count, Container& c) {
    std::srand(std::time(0));

    size_t i = 0;
    while (i++ < count) {
        c.push_back((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(const Container& c) {
    double avg = get_avg(c);

    std::cout << "The average is: " << avg << endl;
    std::cout << "Position\tValue\t\tDifference from average\n\n";

    size_t idx = 0;
    for(auto e : c){
        cout << idx++ << "\t\t" << e << "\t\t" << std::showpos << avg - e << std::noshowpos << std::endl;
    }
}

// There is std::minmax_element that gets both minimum and maximum value at once!
void print_min_max(const Container& c) {
    auto mm = std::minmax_element(c.begin(), c.end());
    std::cout << "The position of the minimum number in the container is "<< mm.first - c.begin() <<" and the value is " << *(mm.first) << std::endl;
    std::cout << "The position of the maximum number in the container is "<< mm.second - c.begin() <<" and the value is " << *(mm.second) << std::endl;
}   

int main() {

    Container c;
    const size_t count = 24;

    fill(count, c);
    print_output(c);
    print_min_max(c);

    std::cout << endl;

    // wrap-up

    std::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;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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