Percentage in C

1

Given the following statement:

  

Write an algorithm to show on the screen whether each N number, typed   by the user is even or odd. The algorithm should also show on the screen   the sum of all even numbers, the sum of all odd numbers,   the percentage of even numbers and the percentage of odd numbers   typed. The algorithm should terminate its execution if the user   enter a number less than zero.

I wrote the following code:

#include <stdio.h>

     int main()
     {

     int N;
     int somapar = 0;
     int somaimpar = 0;
     float porcentagemi = 1;
     float porcentagemp = 1;

     do{
      printf("\n Digite um número qualquer: ");
      scanf("%d", &N);

     if (N % 2 == 0){
      printf("\n Número escolhido é par!");
      somapar += N;
     }

     else {
      printf("\n Número escolhido é ímpar");
      somaimpar += N;
     }

     printf("\n Soma total de ímpares é %d e soma total de pares é %d\n", somaimpar, somapar);

     porcentagemp = (somapar/(somapar + somaimpar))*100;
     porcentagemi = (somaimpar/(somapar + somaimpar))*100;

     printf("\n Porcentagem de pares é: %f", porcentagemp);
     printf("\n Porcentagem de ímpares é: %f\n", porcentagemi);

     }while (N >= 0);

     return 0;
     }

But the program is not returning the percentage correctly. When I type a even number and an odd number then instead of the program it returns me 50% each, it ZERO both.

    
asked by anonymous 14.10.2016 / 17:18

1 answer

2

You need to take the percentage from within the loop, it can only be calculated after you have all the data. In addition, you need to ensure that the division is done as float to have decimal places. In the current form it gives an integer and the account is inaccurate for what you want, so a member must be a floating point.

#include <stdio.h>

int main() {
    int N;
    int somapar = 0;
    int somaimpar = 0;
    do {
        printf("\n Digite um número qualquer: ");
        scanf("%d", &N);
        if (N % 2 == 0) {
            printf("\n Número escolhido é par!");
            somapar += N;
        } else {
            printf("\n Número escolhido é ímpar");
            somaimpar += N;
        }
    } while (N >= 0);
    printf("\nTotal de ímpares é %d e total de pares é %d\n", somaimpar, somapar);
    float total = somapar + somaimpar;
    float porcentagemPar = somapar / total * 100.0f;
    float porcentagemImpar = somaimpar / total * 100.0f;
    printf("Porcentagem de pares é: %f\n", porcentagemPar);
    printf("Porcentagem de ímpares é: %f\n", porcentagemImpar);
}

See running on ideone .

    
14.10.2016 / 17:45