c++ - 引用变量在 C++ 中不返回值

标签 c++ function variables reference

<分区>

我的引用变量在我的函数中存储值时遇到问题。这段代码哪里出错了?

//Loads temperature from a disk file and outputs them to the screen

#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
#include "myHeader.h"
using namespace std;

//Function prototypes
void minMax (int mean[], int size, int &, int &);

//Declare Global variables
string userFile;         //variable for user input of file
string date;             //variable for inputFile date
int low;                 //variable for inputFile low
int high;                //variable for inputFile high
double sumLow = 0.0;     //variable to hold sum of low temps
double sumHigh = 0.0;    //variable to hold sum of high temps
ifstream inputFile;

const int ARRAY_SIZE = 31;
int lowTemp[ARRAY_SIZE];
int highTemp[ARRAY_SIZE];

//Accumulators
int min = 200;
int max = 0;
int count = 0;
int minTemp = 0;
int maxTemp = 0;

int main()
{
//Call the heading function
heading(8, 'A');

//Prompt user to enter a file
cout << "What file do you want to open for input? ";
cin >> userFile;
cout << endl; 

inputFile.open(userFile);

minMax(lowTemp, ARRAY_SIZE, minTemp, maxTemp);

//Close the file
inputFile.close();

return 0;
}

//******************************************
//Definition of function minMax
//******************************************

void minMax (int mean[], int size, int & min, int & max)
{

    for (int i = 0; (i < ARRAY_SIZE) && (inputFile >> date >>     low >> high); i++)
    {
        lowTemp[i] =  low;
        highTemp[i] = high;
        count = i;
        sumLow += lowTemp[i];
        sumHigh += highTemp[i];

        if (lowTemp[i] < min)
        {
            min = lowTemp[i];
        }
        if (highTemp[i] > max)
        {
            max = highTemp[i];
        }

        minTemp = min;
        maxTemp = max;
    }

    cout << "array size " << count + 1 <<  " array low " << minTemp << " array high " << maxTemp << endl << endl;
    cout << endl << count + 1 << " " << sumLow << " " << sumHigh << endl;
}

程序编译并询问用户打开哪个文件。我输入文件,它返回。

数组大小 31 数组低 0 数组高 91

31 1831 2602

数组High正确;但是,根据文件,数组 low 应该是 34。

最佳答案

Low 初始化为零:int minTemp = 0;


我可以推荐读一本好的教科书吗?您的代码读起来好像您不明白发生了什么。

您的许多全局变量未被使用,因为它们被具有相同名称的局部参数隐藏。删除全局变量或用局部变量替换它们将提高您的代码质量。

例如

//Accumulators
int min = 200;
int max = 0;

....

void minMax (int mean[], int size, int & min, int & max)
{

全局 minmax,即您所说的“累加器”,完全未使用。

关于c++ - 引用变量在 C++ 中不返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13126678/

相关文章:

bash - 在 Bash 中将带空格的字符串作为函数参数传递

r - 变量创建 - 推断年龄

iphone - 使用 "self.variable = value"设置实例变量两次会导致内存泄漏吗?

c++ - 在 makefile 中添加 c++11 以消除错误 to_string is not declared in this scope

c++ - 更改模板参数 C++

c++ - 字符指针

javascript - jQuery:暂停按钮暂停所有其他操作

c++ - G++ 是否足够聪明来优化它?

python - 在 Python 中自省(introspection)给定函数的嵌套(本地)函数

php - 在表单中打印 JS 变量