【问题标题】:C++ Function is printing unwanted numbers after endl (memory variable?)C++ 函数在 endl 之后打印不需要的数字(内存变量?)
【发布时间】:2018-04-17 14:36:10
【问题描述】:

除了一个小问题外,这段代码对我来说非常有效。调用我的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;

}

【问题讨论】:

  • 您的find_minfind_max 被声明为返回int,但不返回任何内容。还可以考虑使用std::array(或std::vector)及其.size(),而不是幻数。
  • get_array 函数中,您使用for(i=0; i&lt;25; i++){,而其他所有内容都使用24 作为数组大小。
  • 使用endl 有时会出现问题。在任何情况下使用\n 是更好的选择。
  • @AliSepehri-Amin,在任何情况中绝对不会更好。 endl 刷新缓冲区,有时您需要刷新它。所以它们是不同的,一个不能替代另一个。

标签: c++ function output


【解决方案1】:

在这两行中:

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

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

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

【讨论】:

  • 好奇:为什么标准不将此定义为错误?我的意思是,声明一个函数返回一些东西,而不是在函数体中返回任何东西。隐含的return somegarbage 似乎从来都不是有用的行为
【解决方案2】:

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

更好的是,将编译器警告转化为错误(例如,在 GNU g++ 中,使用选项 -Werror

其他 cmets 建议使用“真正的”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;
}

【讨论】:

  • print_output 中的 24 显然是印刷错误。 :)
  • @Evgeny 你是对的,谢谢你的提示。我现在连这个神奇的数字都消除了。
猜你喜欢
  • 2021-09-06
  • 2023-02-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-22
  • 2015-11-07
  • 1970-01-01
相关资源
最近更新 更多