the debugger says it adds the rainfall correctly but it outputs 34 to the screen and i should get 33.9. Anyone have any ideas?
#include <iostream>
#include <iomanip>
#include <fstream>
using namespace std;
const int YEAR=8,MONTH=12;
void readData(int year[],double rain[MONTH][YEAR]);
void printData(int year[],double rain[][YEAR]);
int main(){
int year[YEAR];
double rain[MONTH][YEAR],total=0;
readData(year,rain);
printData(year,rain);
cout<<endl<<endl;
cout<<"Rainfall for "<<year[2]<<":"<<endl;
for(int month=0;month<MONTH;month++){
cout<<showpoint<<setprecision(2)<<setw(5)<<rain[month][2];}
cout<<endl;
for(int i=0;i<MONTH;i++){
total+=rain[i][2];}
cout<<"Total rainfall for "<<year[2]<<" is "<<total<<endl;
return 0;
}
//this function collects data
void readData(int year[],double rain[][YEAR]){
ifstream input;
input.open("rainfall.txt");
if(input.fail()){
cout<<"exiting program, failed to open file!"<<endl;
exit(1);}
for(int i=0;i<YEAR;i++){
input>>year[i];
for(int month=0;month<MONTH;month++){
input>>rain[month][i];}
}
input.close();
}
//this function prints data collected by previos function.
void printData(int year[],double rain[][YEAR]){
for(int i=0;i<YEAR;i++){
cout<<"Year "<<year[i]<<endl;
for(int month=0;month<MONTH;month++){
cout<<showpoint<<setprecision(2)<<setw(5)<<rain[month][i];}
cout<<endl;
}
}
You set the precision to 2 places, hence 33.9 comes out as 34. Try setprecision(3).