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()
shouldint main(void)
- do not use
fflush(stdin)
, undefined behavior. - the condition
dist[i] < dist[i + 1]
wrong. shoulddist[i] < dist[i2]
because index of best element should stored ini2
, element should compared other elements.
Comments
Post a Comment