我无法让该程序以正确的格式输出内容。setw 函数似乎没有做我想做的事。此外,平均值、低点和高点都给了我错误的答案。该程序应该读入一个文件并处理它们以找到当天的最高温度、最低温度和所有温度的平均值。每天的值与前一天相同。
有人可以指出我做错了什么吗?
#include <iostream>
#include <iomanip>
#include <conio.h>
#include <fstream>
#include <string>
double averageTemp(double total, int number);
double lowTemp(double valueLow);
double highTemp(double valueHigh);
double high = 0;
double low = 0;
int main()
{
std::string dummy = "";
int day, time = 0;
double input1[10][50], input5[10][50], input25[10][50];
/*
Keeps track of the data:
Dimension 1: stores the input for each time of the day.
*/
double m1[10][3], m5[10][3], m25[10][3];
/*
Process data:
Dimension 1:
Index 1: Keeps track of day
Dimension 2:
Index 1: Average temp
Index 2: Low temp
Index 3: High temp
*/
std::ifstream datain;
std::ofstream dataout;
datain.open("curiosity234X.dat");
dataout.open("output.dat");
for (unsigned int i = 0; i < 4; i++)
{
getline(datain, dummy);
}
int dayCount = 0, loopDay;
while (datain >> day >> dummy >> dummy >> input1[day][time]
>> input5[day][time] >> input25[day][time])
{
while (dayCount == 0)
{
loopDay = day - 1;
dayCount++;
}
m1[day][0] = averageTemp(input1[day][time], time);
m1[day][1] = lowTemp(input1[day][time]);
m1[day][2] = highTemp(input1[day][time]);
m5[day][0] = averageTemp(input5[day][time], time);
m5[day][1] = lowTemp(input5[day][time]);
m5[day][2] = highTemp(input5[day][time]);
m25[day][0] = averageTemp(input25[day][time], time);
m25[day][1] = lowTemp(input25[day][time]);
m25[day][2] = highTemp(input25[day][time]);
time++;
}
dataout << std::setw(5) << std::fixed;
dataout << "Average" << "Low" << "High" << std::endl
<< "Temp" << "Temp" << "Temp" <<std::endl
<< "1 meter" << ".5 meters" << ".25 meters" << std::endl;
std::cout << std::setw(5) << std::fixed;
std::cout << "Average" << "Low" << "High" << std::endl
<< "Temp" << "Temp" << "Temp" <<std::endl
<< "1 meter" << ".5 meters" << ".25 meters" << std::endl;
for (unsigned int i = loopDay; i < day; i++)
{
dataout << std::fixed << std::setprecision(1) << std::setw(5);
dataout
<< m1[day][0] << m1[day][1] << m1[day][2]
<< m5[day][0] << m5[day][1] << m5[day][2]
<< m25[day][0] << m25[day][1] << m25[day][2]
<< std::endl;
std::cout << std::fixed << std::setprecision(1) << std::setw(5);
std::cout
<< m1[day][0] << m1[day][1] << m1[day][2]
<< m5[day][0] << m5[day][1] << m5[day][2]
<< m25[day][0] << m25[day][1] << m25[day][2]
<< std::endl;
}
std::cout << std::endl << std::endl << std::endl
<< "The output.dat file has been written and transmitted."
<< std::endl;
_getch();
return 0;
}
double lowTemp(double valueLow)
{
if (valueLow < low)
{
::low = valueLow;
return valueLow;
} else
{
return low;
}
}
double highTemp(double valueHigh)
{
if (valueHigh > high)
{
::high = valueHigh;
return valueHigh;
} else
{
return high;
}
}
double averageTemp(double total, int number)
{
double average = total/double(number);
return average;
}