Jump to content

Quantos 1 em binário


britoOo
 Share

Recommended Posts

Pessoal estou com dúvidas num exercicio. o exercicio pede para introduzir um número e dizer quantos 1 tem em binário. por exemplo:

10/2 -> 0

5/2 -> 1

2/2 -> 0

1

ou seja tem 2 numeros 1.

Eu fiz este código compila mas a soma não está a funcionar não sei porque, continua sempre com '0'.

#include <stdio.h>

int bitsUm(unsigned int n){

int aux,soma;
while(n>=0){
if(n%2==1){
soma=soma+1;
aux=n/2;
n=aux;


}
else 
{
aux=(n/2);
n=aux;


}
return soma;
}


}
int main()

{

int n,soma;
printf("numero: \n");
scanf("%d",&n);
printf("o numero em binario '%d' apresanta '%d' numeros 1 \n",n,bitsUm(soma));

return 0;


}

na consola dá isto

numero: 
10
o numero em binario '10' apresanta '0' numeros 1 

Obrigado pela atenção!

BritoO

Edited by thoga31
Tags code + GeSHi
Link to comment
Share on other sites

Obrigado pela ajuda já consegui fazer!

#include <stdio.h>

int bitsUm(unsigned int n){

int aux,soma=0;
while(n>0){
if(n%2==1){
soma=soma+1;
n=n/2;


}
else 
{

n=n/2;

}
}
printf("O numero de uns e: %d \n",soma);

return soma;


}
int main()

{

int n;
printf("numero: \n");
scanf("%d",&n);

bitsUm(n);

return 0;


}
Edited by thoga31
Tags code + GeSHi
Link to comment
Share on other sites

para referência de quem procurar uma solução :

#include <stdio.h>

unsigned int bitsUm(unsigned int n){
 unsigned int soma = 0;

 while(n) {
   soma += n % 2;
   n >>= 1;
 }

 return soma;
}

int main(void) {
 unsigned int n;

 printf("numero: \n");
 if (scanf("%u", &n))
   printf("O numero de uns e: %d\n", bitsUm(n));

 return 0;
}
IRC : sim, é algo que ainda existe >> #p@p
Link to comment
Share on other sites

On 3/4/2019 at 2:16 PM, Luís Paiva said:

@HappyHippyHippo não seria suficiente isto:


int bitsUm(unsigned x)
{
    int r=0;
    while (x != 0){
        if (x%2 == 1)
            r++;
        x = x/2;
    }
    return r;
}

eu fiz este programa mas retorna-me valor 1.

e o que achas que o código que apresentei faz (de uma forma mais simples) ?

IRC : sim, é algo que ainda existe >> #p@p
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...

Important Information

By using this site you accept our Terms of Use and Privacy Policy. We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.