How not to show in the output the null positions of a vector?

Asked

Viewed 136 times

0

How do I prevent those gigantic numbers referring to the empty positions of my vector from appearing?

My code:

int main(int argc, char** argv) {

double notas[10];
double soma = 0, media = 0;
int i, P[10];
int j = 0, count = 0;

for(i=0;i<10;i++){
    printf("Digite %d: ", i);
    scanf("%lf", &notas[i]);
}

for(i=0;i<10;i++){
    if(notas[i] > 5){
        soma = soma + notas[i];
        count++;
    }
}
media = soma/ count;

for(i=0;i<10;i++){
    if(notas[i]>= media){
        P[j] = i;
        j++;
    }
}
    printf("%.2lf\n", media);


for(i=0;i<10;i++){
    printf("%d  ", P[i]);
}
return (EXIT_SUCCESS);
}

Exit:

Exemplo de saída

Curiosity: What are the names of these large numbers that appear?

  • Did the answer solve your problem? Do you think you can accept it? If you don’t know how you do it, check out [tour]. This would help a lot to indicate that the solution was useful to you and to give an indication that there was a satisfactory solution. You can also vote on any question or answer you find useful on the entire site.

1 answer

3

The final print is printing the 10 positions of the array of notes that were above average, can only print the amount of notes that were inserted there, that is, can only go up to j (bad name for variable since it does not indicate what it is). Another solution would only be to mark unused positions as invalid and then check if it is invalid (it could even mark the first invalid position and stop reading the others), but I don’t like this. I don’t even like wearing one anymore array fixed for this, but I understand the use in exercise. Maybe you have some logic problem too, but I can’t talk about it. Something like this:

#include <stdio.h>

int main(void) {
    double notas[10];
    for (int i = 0; i < 10; i++) {
        printf("Digite %d: ", i);
        scanf("%lf", &notas[i]);
    }
    int j = 0, count = 0;
    double soma = 0;
    for (int i = 0; i < 10; i++) {
        if (notas[i] > 5) {
            soma = soma + notas[i];
            count++;
        }
    }
    double media = soma / count;
    int P[10];
    for (int i = 0; i < 10; i++) {
        if (notas[i] >= media) {
            P[j] = i;
            j++;
        }
    }
    printf("%.2lf\n", media);
    for (int i = 0; i < j; i++) {
        printf("%d  ", P[i]);
    }
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

The "big" numbers that appear is memory junk, since it is accessing positions of the array which were not initialized into the program he picks up whatever crap he had in his memory before its execution. In C the integral memory management has to be done manually.

Browser other questions tagged

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