Hi guys! I had this assignment which asks to calculate the average of numbers divisible by 5 in a range entered by the user.
I have solved it and all, but the problem is I want the input to be only in numbers,,, I tried to make it with an if statement and make the last else open for any weird inputs, and I built my main code inside the first else if, but what I did there just fails,
I searched the internet but only found thing that made me ask more, like:
// Calculating the average of numbers divisible by 5 in a range entered by the user
#include <iostream>
usingnamespace std;
int main()
{
// Variables
int rangeBig, rangeSmall, counter = 0, sum = 0;
// Inputs
cout << "Enter the smallest number in the range: ";
cin >> rangeSmall;
cout << "Enter the biggest number in the range: ";
cin >> rangeBig;
// Conditions
if (rangeSmall >= rangeBig) { cout << "Both ranges can't be equal, must only contain numbers, and the smallest number in the range can't be bigger than its biggest!" << endl; }
elseif (rangeBig > rangeSmall)
{
for (rangeSmall;rangeSmall <= rangeBig;rangeSmall++) // For loop
{
if (rangeSmall % 5 == 0) // Nested if
{
sum += rangeSmall;
counter++;
}
}
// Output
cout << "Average of numbers divisible by 5 = " << sum / counter << endl;
return sum / counter;
}
else { cout << "You must enter a number!" << endl; }
}
// try, try again, until you do get a number:
while( !(std::cin >> rangeSmall) )
{
std::cin.clear();
std::cin.ignore(std::numeric_limits<streamsize>::max(),'\n');
}
// try, try again, until you do get a number that is large enough:
while( !(std::cin >> rangeBig and rangeSmall < rangeBig) )
{
std::cin.clear();
std::cin.ignore(std::numeric_limits<streamsize>::max(),'\n');
}
Btw, you do not need a loop for computing the average. Sum of arithmetic serie has an equation.
Line 31: why does the program return the average to the calling shell? The convention is to return 0 on successful exit.
Line 30: dividing an int with an int creates an int and that discards the fraction.
Force floating point math: static_cast<double>(sum) / count
Line 30. What if range was from 1 to 3? Division by 0.
If there are no numbers, then there is no sum and no average.
You can test after the loop whether there were any numbers (i.e. if count is larger than 0).