Averaging the sequence of while

Asked

Viewed 1,025 times

0

I’m solving college exercises, but I got caught up in one:

The exercise asks me to calculate the even numbers between two integers, and that at the end, I do the arithmetic mean between the pairs.

What I’ve done so far:

int main()
{
    int numeroum, numerodois; 

    printf("Insira dois números pares\n");
    scanf("%d", &numeroum);
    scanf("%d", &numerodois);
    printf("Os pares entre %d e %d são: \n", numeroum, numerodois);
    while (numeroum < numerodois) {
        printf("%d\n", numeroum);
        numeroum = numeroum + 2;
    }

    printf("A média de todos os números é: %d\n", );

    return 0;
}
  • Do you want help in logic? Or some doubt in the code (commands)?

  • How about printf("%d", (((numeroum + 1) & ~1) + (numerodois & ~1)) / 2);?

  • @Andrey Part in the code and part in the logic, but more in the code. I don’t know exactly which command to use to have a split of the While results.

  • @Victorstafusa I tried with this command and it didn’t work... I didn’t get to work with ~ yet, I’m not sure what it would serve... if I’m right, sorry, but I’m pretty layman hahahaah

1 answer

0


You can use %2 operator (module) which returns the rest of the division.

If (numeroum%2==0) means it is an even number

inside a loop would look like this

int a=0;// pra salvar  a soma de todos os valores pares
int b=0;// pra salvar a quantidade de elementos.



  while (numeroum < numerodois) {
    if(numeroum%2==0){// na linaha de  baixo você printa o número
           a=a+numeroum;
           b++;
            printf("%d\n", numeroum);//aqui basta você guardar numeroum em um array (vetor).

    }numeroum++;
   }

 printf("%d\n", a/b); // aqui você mostra  a média
  • Would you have a command for him to automatically calculate the numbers and drop the result when executing the code, instead of me putting it to add and divide at the end? Or would he do that and I didn’t get it right? I’m kind of layman yet hahahaha

  • I changed the code see if you understood

  • Perfect guy, it worked... I’ll take a look to understand the logic and what was done... just gave a glue to test. Thank you very much!

Browser other questions tagged

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