I have the following code. Everything compiles but when it runs the sums are not correct. I need to calculate the sums for all the odd integers, the even integers, and all the integers.
my infile was provided with the following integers. I am not supposed to assume the infile has 20 integers.
Also, I wanted to the average to calculate with two decimal place precision and that is also incorrect??? setprecision(2) I thought would work???
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
#include <cmath>
usingnamespace std;
int main( )
{
//Accept user inpput to open file
ifstream infile;
string file_name;
//Set precision
std::fixed;
//Declare variables
int i = 0;
int odd = 0;
int even = 0;
int sumOdd = 0;
int sumEven = 0;
int sumAll = 0;
int max = 0;
int min = 0;
int myArray[20] = {0};
double average = 0.00;
double fileName = 0;
//Set precision
std::fixed;
//Displaly and ask for user input
cout << "Welcome to Wake's Integer processing Agency" << endl;
cout << "What is the name of the input file? ";
cin >> file_name;
//Read input from infile
infile.open(file_name.c_str(),ios::in);
//Read, sort, and calculate
while (infile >> myArray[i])
{
if (myArray[i]%2 != 0)
{
odd++;
sumOdd = odd + myArray[i];
}
if (myArray[i]%2 == 0)
{
even++;
sumEven = even + myArray[i];
}
if (i == 0)
{
max = min = myArray [i];
}
if (myArray[i] > max)
max = myArray[i];
if (myArray[i] < min)
min = myArray[i];
++i;
sumAll = sumOdd + sumEven;
}
//Display
cout << "Number of integers in the file is " << i << endl;
cout << "There are " << odd << " odd integers and " << even << " even integers" << endl;
//Calculate sum of Odd, Even, and All integers
cout << "The sum of the odd integers is " << sumOdd << endl;
cout << "The sum of the even integers is " << sumEven << endl;
cout << "The sum of all the integers is " << sumAll << endl;
//Display largest and smallest integer
cout << "The largest integer is " << max << endl;
cout << "The smallest integer is " << min << endl;
//Calculate the average of the largest and smallest integers
average = (max + min) / 2;
cout << "The average of " << max << " and " << min << " is " << setprecision(3) << average;
cout << endl;
//Close
infile.close();
system("pause");
return 0;
}
Thank you, this is the first time I've asked for help! I formatted using code tags and also edited my post. I actually put in the wrong code. I have been stuck on this code for days and have written from scratch several times, I have many copies. The above is the most complete. I am still have trouble with the precision even after trying your suggestion???
The precision for decimal places is floor(x*100+.005)/100 the precision you used is for place precision ex. 1560 becomes 15 with precision of 2. Another way ot doing this is to use cout << fixed << setprecision << x;