Answer to Question #148466 in C++ for Sang Nguyen

Question #148466
Solicit an integer number between 1 and 100 from the user. If the number is less than 50, calculate the average of the number and all positive values below it. If the number is 50 or higher, calculate the average of the number and all number between it and 100; and including 100
1
Expert's answer
2020-12-03T14:33:32-0500
#include <iostream>
#include <iomanip>

using namespace std;

// calculating Average between N1 and N2 numbers
double Average(int N1, int N2)
{
    int Sum = 0;
    for (int i = N1; i <= N2; i++)
        Sum += i;
    return Sum / (static_cast<double>(N2) - static_cast<double>(N1) + 1);
}

int main()
{
    int Number;

    while (true)
    {
        cout << "Please enter integer number between 1 and 100: ";
        cin >> Number;

        // input check for consistency
        if (cin.fail() || (Number < 1) || (Number > 100))
        {
            std::cin.clear();
            std::cin.ignore(32767, '\n');
            cout << "Wrong input" << endl << endl;
            continue;
        }

        cout << fixed << setprecision(2);
        if (Number < 50)
            cout << "Average 1 -> " << Number << " is " << Average(1, Number);
        else
            cout << "Average " << Number << " -> 100 is " << Average(Number, 100);

        return 0;
    }    
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog