Use of EOF in vectors

Asked

Viewed 390 times

-1

Good evening, I wonder if in this program I am using the EOF(end of file) right, IE, while I do not type 0, the vector will be allocated and recorded with a value?? Follows code below:

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

int main (void)
{
    int i,j, counter = 1,mediaaritmetica, novasequencia;
    int* sequencia = NULL;

    while (scanf(%d), &sequencia[i] != EOF)
    {
        sequencia = (int*) realloc(sequencia, counter * sizeof(int));
        scanf("%d", &sequencia[i]);
        counter++
    }   

    for (j = 0; j < counter ; j++)
    {
        mediaartimetica += sequencia[j];
    }

    mediaaritmetica = mediaartimetica/counter - 1;

    for ( k = 2, k < counter ; k++)
    {
        novasequencia = pow(sequencia[k], 2)/mediaaritmetica * (sequencia[k - 2] + sequencia[k -1] + sequencia[k])
        printf(".4%d\n", novasequencia);
    }

    return 0;
}
  • The code you have presented does not even compile yet. I think there is scope for you to hit a lot before attacking the EOF problem. :)

2 answers

1

Some notes:

  1. while (scanf(%d), &sequencia[i] != EOF) quotation mark error and parenthesis
  2. sequencia = NULL; /* ... */ &sequencia[i] You’re getting ahead of yourself
  3. use of i without assigning a value
  4. mediaaritmetica = mediaartimetica/counter - 1; need for parenthesis
  5. pow() needs <math.h>. But you can do the same by multiplying the value: sequencia[k] * sequencia[k]
  6. different identifiers!!! mediaaritmetica and mediaartimetica

0

The EOF is only used for when dealing with files, just as the name already says End Of File, end of file, not vector.

Starting with your while, the scanf is a method for reading information and the sequencia[i] does not yet exist, and the conditions in a while out any other structure separates with && or || (this in C,C++, etc). The correct is to have a variable to collect the value of scanf and through it check the entrance.

int in = 1;
sequencia = (int*) malloc(0);
// continua enquanto 'in' diferente de '0'
while(in != 0){
    scanf("%i", &in);                     // counter deve iniciar em 0 para
                                          // não ter problema no for abaixo.
    sequencia = (int*) realloc(sequencia, (couter + 1)*sizeof(int));
    sequencia[counter] = in;
    counter++;
}

Another thing, first of a malloc in sequencia.

Your average has to have parentheses in counter - 1 to remove one before division.

mediaaritmetica = mediaartimetica/(counter - 1);

And finally, you must declare k before using it on for.

int k;
for ( k = 2, k < counter ; k++){

and all other variables start with 0, because when a variable is created, the compiler inserts value garbage into them.

int i,j, counter = 1,mediaaritmetica=0, novasequencia=0;

Browser other questions tagged

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