Function is zeroing last vector value

Asked

Viewed 98 times

1

#include <stdio.h>
#include <stdlib.h>


/**
2. Faça um programa que, a partir de um vetor de 12 posições, crie funções para: 

A. Digitar valores no vetor; 
B. Imprimir o valor somatório de seus itens; 
C. Imprimir a média dos valores fornecidos;
D. Substituir por 0 todos os números negativos; 
E. Substituir por 0 todos os números repetidos (maiores que 0). 
**/

float SomarVetor(float vet[]){
  float soma=0;
  for(int i=0; i < 12; i++){
    soma += vet[i]; //Somar valores do vetor
  }
  return soma; //Irá retornar a soma total
}


float media(float vet[]){
  float media =0;
  for(int i=0; i < 12; i++){
    media += vet[i]; //Soma os valores
  }
  return media/12;
}


float negativos(float vet[]){
  for(int i=0; i < 12; i++){
    if(vet[i] < 0){
      vet[i] = 0.0; //Substituir valores negativos por 0
    }
  }
}


float repetidos(float vet[]){

  for(int i=0; i < 12; i++){
    for(int j=0; j < 12; j++){
      if(vet[i] == vet[j+1]){
        vet[i] = 0.00;
        j++;
      }else{
        for(int k=11; k > 0; k--){
          if(vet[i] == vet[k]){
            vet[i] = 0.00;
            k--;
          }
        }
      }
    }
  }
}


main(){

  float vet[11];// Vetor de 12 posicoes
  int i; 

  for(i=0; i < 12; i++){//Preenchimento do vetor 
    printf("Digite o %d do vetor: ", i);
    scanf("%f", &vet[i]);
  }


  //Respostas
  printf("Soma dos itens do vetor é %.2f\n", SomarVetor(vet));
  printf("Media: %.2f\n", media(vet));
  negativos(vet);
  //repetidos(vet);

  for(i=0; i < 12; i++){
    printf("%.2f | ", vet[i]);
  }
}

Why the function negativos() is making the last vector position zero too? Since the condition to zero is that it is negative number?

  • 1

    float vet[11];// Vetor de 12 posicoes no, it has 11 positions, why I say that you should not comment code meaning what it does, because it can say one thing and the code do another, it’s just confusion.

  • But it doesn’t count to zero?

  • 1

    Start from 0, there you have to put the amount of elements, not the last of them.

  • When I see that I usually feel like crying: &#xA; }&#xA; }&#xA; }&#xA; }&#xA; }&#xA;}

  • What a mess, solved

  • Tie it up 'cause it’s just a line, you don’t need it

Show 1 more comment

1 answer

1


The statement of a array should contain the amount of elements expected to be used from it. As the elements start at 0, the last will be the size minus one. But the quantity of elements is the quantity of elements, it has no displacement, normally counts.

Just be careful because in C there is not much protection, if you try to access outside of this range, it leaves and corrupts the memory.

  • What do you call corrupting memory? It will have "junk" values stored in undefined locations?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.