Write a function calculateAverage() which takes four int arguments which are mar
ID: 3720020 • Letter: W
Question
Write a function calculateAverage() which takes four int arguments which are marks for four courses in the semester and returns their average as a float.
The calculateAverage() function should take only valid range for marks which is between 0 - 100. If the marks are out of range throw an OutOfRangeException - define this exception as a class as shown in the lecture and lecture examples.
Write the specification for this function as comments above it specifying the pre conditions, post conditions and invariants and what exceptions are thrown when so that the caller understand how it behaves. (USE C++)
Explanation / Answer
#include <iostream>
using namespace std;
class myexception: public exception
{
virtual const char* what() const throw()
{
return "Invalid marks input.";
}
} myex;
float calculateAverage(int m1, int m2, int m3, int m4) {
if(m1<0 || m1>100 ||m2<0 || m2>100
||m3<0 || m3>100||m4<0 || m4>100) {
throw myex;
} else {
return (m1+m2+m3+m4)/(float)4;
}
}
int main()
{
try {
calculateAverage(-1,2,3,4);
}catch(exception& e) {
cout<<e.what()<<endl;
}
try {
float avg = calculateAverage(11,22,33,45);
cout<<"Average: "<<avg<<endl;
}catch(exception& e) {
cout<<e.what()<<endl;
}
return 0;
}
Output:
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.