Percentage in C

Asked

Viewed 2,214 times

2

Given the following statement:

Write an algorithm to show on the screen if each N number, typed 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 type 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 an even number and an odd number then instead of the program returning me 50% each, it ZERA the two.

  • It must be zeroing the variables because of the scope puts the variables you do not want to get lost outside the main function or in the global scope

1 answer

4


You need to take the percentage out of the loop, it can only be calculated once you have all the data. In addition it is necessary to ensure that the division is made as float to have decimal places. In the current form it gives an integer and the account is inaccurate to what you want, so a member needs to be 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);
}

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

Browser other questions tagged

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