Home > Software design >  the code still print 0 and it can't calculate the required task
the code still print 0 and it can't calculate the required task

Time:05-29

#include <iostream>
using namespace std;

int main()
{
    int n, G;
    float num[500], sum=0.0, average,Grades;

    cout << "Enter the numbers of data: ";
    cin >> n;

    while (n > 500 || n <=  0)
    {
        cout << "Error! number should in range of (1 to 500)." << endl;
        cout << "Enter the number again: ";
        cin >> n;
    }

    for(G = 0; G < n;   G)
    {
        cout << G   1 << ". Enter number: ";
        cin >> num[G];
        sum  = num[G];
    }


    average = sum / n;
    Grades = num[G] >= average;
    
    cout<<endl;
    
    cout << "Grades Average = " << average << endl;
    cout << "Grades above or equal the Average : " <<Grades<< endl;
    cout << "Number of grades above the Average = "<<(int) Grades;
    
    return 0;
}

i coded this code but the Number of grades above the Average and Grades above or equal the Average don't work it just print 0

i tried to print the Grades >= the avg but it print 0

also num of Grades also print 0

where is the error ?

CodePudding user response:

I think you was trying to do something like this:

...
int grades_on_avg, upper_grades = 0; 
for(int i = 0; i < n;   i)
{
    cout << i   1 << ". Enter number: ";
    cin >> num[i];
    sum  = num[i];
       
}
average = sum / n;
for(int i = 0; i < n;   i) // use separate for loop and redifend index
{
    if(num[i] == average) // compare to average
        grades_on_avg  ;
    else if(num[i] > average) // if bigger than average
        upper_grades  ;
}



cout<<endl;

cout << "Grades Average = " << average << endl;
cout << "Grades above or equal the Average =" << (grades_on_avg   upper_grades) << endl;
cout << "Number of grades above the Average = "<< upper_grades ;

CodePudding user response:

You assign boolean value to Grades variable. Also, you refer to element outside of the array: G variable is equal to n after exiting for-loop, but max index you can use is n - 1 (basic programming rule). So, you should change your code into something like this:

...
int avgGrades{0};
int avgAboveGrades{0};

for(int i{0}; i < n;   i)
{
    if(num [i] == average)
    {
          avgGrades;
    }
    else if(num [i] > average)
    {
          avgAboveGrades;
    }
}

If you prefer more elegant ways of doing so, you can use std::count_if() function but it's more tricky and requires knowledge about lambdas.

  • Related