Write a C++ function that meets the following: -The function is named averageRea
ID: 3815902 • Letter: W
Question
Write a C++ function that meets the following:
-The function is named averageReading
-It has four parameters
1) an array of integer values called readings
2) an integer that is the size of the array called size
3) an integer called minReading
4) an integer called maxReading
- The function should determine and return the average of all enteries in the array readings that fall in the |minReading maxReading| interval. That is, the values less than minReading, and the values larger than maxReading are ignored in the average.
- If there are no values in the |minReading maxReading| interval, the function should return 0
Explanation / Answer
#include <iostream>
using namespace std;
double averageReading(int readings[], int size, int minReading, int maxReading) {
int sum = 0;
int count = 0;
for(int i=0; i<size; i++){
if(readings[i] >= minReading && readings[i] <= maxReading) {
sum = sum + readings[i];
count++;
}
}
if(count == 0){
return 0;
}
else{
return sum/(double)count;
}
}
int main () {
int a[] = {1,2,3,4,5,6,7,8,9,10};
cout<<"Average is "<<averageReading(a, 10, 5, 8)<<endl;
return 0;
}
Output:
sh-4.2$ g++ -o main *.cpp
sh-4.2$ main
Average is 6.5
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.