0

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

//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 是正确的;但是,根据文件,数组低位应该是 34。

4

1 回答 1

2

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


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

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

例如

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

....

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

全局的minand max,你称之为“累加器”的东西完全没有被使用。

于 2012-10-29T17:33:21.730 回答