3
I’m performing the following exercise:
After a few attempts I reached the following final code:
int proximo_da_media(int *vec, int dim){
int i, *pos;
float media, soma=0, diferenca;
pos=vec; //inicializar ponteiro
for(i=0;i<dim;i++)
soma+=*(vec+i); //faz a soma de todos os numeors
media=0.5+(soma/dim); //faz a media e soma 0.5,como a seguir faz subtração com um int se a media tiver a parte decimal igual ou superior a 0.5 arredonda para cima se não mantem o int original
diferenca=abs((*vec)-media); //calcula a diferença entre a media e o primeiro valor do vetor em valor absoluto
for(i=0;i<dim;i++){
if(abs(*(vec+i)-media)<diferenca){ //se o valor absoluto entre a media e vec[i] for menor que a diferenca anterior então foi descoberto um numero mais proximo da media logo atualizo a diferenca e o ponteiro para o numero encontrado
diferenca=abs(*(vec+i)-media);
pos=vec+i;
}
}
return pos;}
int main(){
int tabela[10]={20,30,43,5,400,1999,9,360,3,8},*posicao;
posicao=proximo_da_media(tabela,10);
printf("O endreco do ponteiro que aponta para o numero mais proximo da media e o %p e tem o valor %d\n",posicao,*posicao);}
With the vector inserted in the code the sum of all numbers is 2877 , making the average (2877/10) we get the result of 287,7 that rounds to 288, being 360 the number closest to the average.
I did some tests and the program has been running as expected, for this example also went well,got the following output:
Although I perform as expected I have 2 warnings and I do not know if I should change something in the code, the warnings are as follows:
I wonder if the algorithm is correct and if I should change something in the code.
Thanks for the explanation, I changed the int to int* and the warnings disappeared, however I also commented on my original code for easier understanding , really yours is more readable, I’ll make some changes but as I started learning pointers recently I was advised to use only pointers in my programs to get used to and understand well the manipulation of pointers
– Droopy
I don’t know if it was good advice.
– Maniero
Over the course of these days I have made several mistakes in the manipulation of the pointers that I will not commit again, I think it has helped me in this aspect
– Droopy
And probably picked up several vices... :)
– Maniero