c - Can't see logical issue on this simple program -


i wrote program, , supposed read numbers, calculate medium value , print closest number it.

#include<stdio.h> int main(){     const int num = 6;      int i, i2 = num - 1;     float numeros[num], dist[num];     float media = 0;      (i = num - 1; >= 0; i--){         printf("digite um numero\n");         scanf("%f", &numeros[i]);         media = media + numeros[i];     }     media = media / num;     (i = num - 1; >= 0; i--){         if (numeros[i] <= media){             dist[i] = media - numeros[i];         }         else{             dist[i] = numeros[i] - media;         }     }     (i = num - 2; >= 0; i--){         if (dist[i] < dist[i + 1]){         i2 = i;         }     }     printf("o numero mais proximo da media '%1.0f' eh '%1.0f'", media, numeros[i2]);      printf("\n\npressione 'enter' para sair");     fflush(stdin);     getchar(); return 0; } 

but like

input 50 50 50 500 24 20 (ok)

media 116 (ok)

prints 24 (?)

  • int main() should int main(void)
  • do not use fflush(stdin), undefined behavior.
  • the condition dist[i] < dist[i + 1] wrong. should dist[i] < dist[i2] because index of best element should stored in i2 , element should compared other elements.

Comments

Popular posts from this blog

Hatching array of circles in AutoCAD using c# -

ios - UITEXTFIELD InputView Uipicker not working in swift -