简体   繁体   中英

Number the nearest to the average C++

does anybody knows what is wrong with 'else' gap and the script inside to show which number is the nearest to the average? I tried to fix it, however there was no better result. (It indicates the number, but wrongly)

  #include <iostream>
  #include <math.h>

 using namespace std;

float average (float *a, int lib)
{
    float suma=0;
    for (int i=0;i<lib;i++)
    {
        suma+=*a;
        a++;
    }
    cout<<endl;
    return suma/lib;
 }


  int ile;

 int main()
 {     
     float *number;
     cout << "quantity of numbers: ";
     cin>> ile; 
     cout<<endl;

     number=new float [ile];
     for (int i=0; i<ile; i++)
     {

        cout<<"Give number: ";
        cin>>number[i];
     }

     double b=number[0];

    if (ile==2) {
        cout<<"liczby "<<number[0]<<" oraz "<<number[1]<<" sa w tej samej     odleglosci liczbowej od sredniej!";
    }
    if (ile==1) {
        cout<<"liczba "<<number[0]<<" jest w tej najbliższej odleglosci liczbowej od sredniej!";
    }

And here we go (upper there already is double b=number[0];)

      else {

     double  a=average(number,ile);

That is supposed to show the number the nearest to the average

          for (int i=0;i<ile;i++)
          {
              if ((fabs(a-b))<=(fabs(a-number[i]))) {
                  b=b;
              }
              else if ((fabs(a-b))>(fabs(a-number[i]))) {
                  b=liczba[i];
              }
              i++;
           }
    }
    cout<<b;
    delete [] number;
    return 0;
}

Thanks in advance for any help

the problem with your code is that you increment the i two times first int the for lop itself and the second time after the if else statment you for loop need to look like that:

for (int i=0;i<ile;i++)
{
    if ((fabs(a-b))<=(fabs(a-number[i]))) {
        b=b;
    }
    else if ((fabs(a-b))>(fabs(a-number[i]))) {
        b=liczba[i];
    }
    //i++; <-- delete this one
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM