Count Positive and Negative Numbers and Compute the Average of Numbers

less than 1 minute read

The code has been modified slightly and now uploaded to the site.

Question

Question

<— Return Home

51.cpp

// Compile Instructions V1
// Use the code: g++ -pedantic -Wall -Wextra -std=c++17 51.cpp -o 51 && ./51

#include <iostream>

int main(){

    int x;
    int countPositives = 0;
    int countNegatives = 0;
    double countTotal = 0;
    int countInstances = 0;
    // int avg;

    std::cout << "Enter an integer, the input ends if it is 0:" << std::endl;
    // while (x != 0){
    while (std::cin >> x && x != 0){
        // std::cin.ignore(80, '\n');
        // std::cin.get();
        // std::cin >> x;
        countTotal += x;
        countInstances++;
        if (x > 0){
            countPositives++;
        }
        else if(x < 0){
            countNegatives++;
        }
        // std::cin.sync();
    }

    if (countTotal == 0){
        std::cout << "No numbers are entered except 0" << std::endl;
    }

    else {
    std::cout << "The number of positives is " << countPositives << std::endl;
    std::cout << "The number of negatives is " << countNegatives << std::endl;
    std::cout << "The total is " << countTotal << std::endl;
    std::cout << "The average is " << (countTotal / countInstances / 1.00) << std::endl;
    }
    
    return 0;
}

<— Return Home