In: Computer Science
Write a C++ program that inputs a sequence of integers into a vector, computes the average, and then outputs the # of input values, the average, and the values themselves. There are 0 or more inputs values, followed by a negative value as the sentinel; the negative value is not stored and not counted. The following sample input:
10 20 0 99 -1
would produce the following output:
N: 4 Avg: 32.25 10 20 0 99
The main program has been written for you, your job is to implement the two functions InputData and GetAverage. See the comments in the "student.cpp" file for specific implementation details.
main.cpp
#include <iostream>
#include <vector>
using namespace std;
// functions from student.cpp:
int InputData(vector<int>& V);
double GetAverage(vector<int> V, int N);
int main()
{
// assume at most 100 inputs:
vector<int> inputs(100);
int N;
double avg;
N = InputData(inputs);
avg = GetAverage(inputs, N);
cout << "N: " << N << endl;
cout << "Avg: " << avg << endl;
for (int i = 0; i < N; ++i)
{
cout << inputs.at(i) << endl;
}
return 0;
}
student.cpp
int InputData(vector<int>& V)
{
// TODO
return 0;
}
//
// GetAverage
//
// Returns the average of the first N values in the vector; if N is
0 then
// 0.0 is returned.
//
double GetAverage(vector<int> V, int N)
{
// TODO
return 0.0;
}
Source Code in C++:
#include <iostream>
#include <vector>
using namespace std;
// functions from student.cpp:
int InputData(vector<int> &V);
double GetAverage(vector<int> V, int N);
int main()
{
// assume at most 100 inputs:
vector<int> inputs(100);
int N;
double avg;
N = InputData(inputs);
avg = GetAverage(inputs, N);
cout << "N: " << N << endl;
cout << "Avg: " << avg << endl;
for (int i = 0; i < N; ++i)
{
cout << inputs.at(i) << endl;
}
return 0;
}
int InputData(vector<int> &V)
{
int N=0;
int inp;
do
{
cin >> inp;
if(inp>=0)
{
V.at(N)=inp;
N++;
}
}while(inp>=0);
return N;
}
//
// GetAverage
//
// Returns the average of the first N values in the vector; if N is
0 then
// 0.0 is returned.
//
double GetAverage(vector<int> V, int N)
{
if(N==0)
return 0.0;
double sum=0;
for(int i=0;i<N;i++)
sum+=V[i];
return sum/N;
}
Output: