我的参考变量存在问题,我的函数中存储了值。这个代码我哪里错了?
//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
阵列高是正确的;但是,根据文件,数组低应该是34。
答案 0 :(得分:2)
低被初始化为零:int minTemp = 0;
我可以推荐阅读一本好的教科书吗?你的代码读起来就像你不明白发生了什么。
许多全局变量未使用,因为它们被具有相同名称的本地参数隐藏。删除全局变量或用局部变量替换它们将提高代码质量。
E.g。
//Accumulators
int min = 200;
int max = 0;
....
void minMax (int mean[], int size, int & min, int & max)
{
全球min
和max
,您称之为“累加器”,完全不再使用。