#include<stdio.h>
#include<math.h>
int n,i,v[10],x,p;
//Funzione per convertire un numero decimale in binario
int DectoBin(int n){
for(i=10; i<0; i--){
p=pow(2,i);
printf("%d\n",p);
if(n%p==0){
v[i-1]++;
n=n-p;
}
else{
if(n>p){
n=n-p;
}
}
}
return *v;
}
//Corpo del programma
int main(){
printf("Inserisci il numero decimale da convertire: ");
scanf("%d",&n);
DectoBin(n
for(i=0; i<10; i++){
printf("%d",v[i]);
}
return 0;
}
You have a number of syntactical errors, but they don't matter so much because your algorithm is not correct.
The condition on line 9 can never be true.
You should be calculating p=pow(2,i-1).
Then, line 9 needs to use a bitwise AND (and a not-equal comparison). if((n&p)!=0)
Also important: v[] should be 11 elements long.
Be aware that since you are using a global variable it is automatically zeroed, but nowhere else is that true.
There is no need to modify n on lines 11 and 15.
The return value of DectoBin() makes no sense (and is unused anyway).
Also, when you are finally done, you'll notice that the number comes out backwards. You can fix that on line 10 by using v[10-i]++;.
Suggestions:
Learn how to get rid of all those global variables. For example, your function could look like this:
void DecToBin( int n, char v[11] )
And you could use it like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
int main(){
int i, n;
int digits[11];
printf("Inserisci il numero decimale da convertire: ");
scanf("%d",&n);
DecToBin(n,digits);
printf("Il numero in binario es ");
for (i=0; i<10; i++){
printf("%d",digits[i]);
}
printf("\n");
return 0;
}
Duoas i modified my program with your tips but it doesn't work.
#include<stdio.h>
#include<math.h>
int n,i,v[11],x,p;
//Funzione per convertire un numero decimale in binario
void DectoBin(int n, int v[11]){
for(i=10; i<0; i--){
p=pow(2,i);
printf("%d\n",p);
if((n&p)!=0){
v[10-i]++;
}
}
}
//Corpo del programma
int main(){
printf("Inserisci il numero decimale da convertire: ");
scanf("%d",&n);
DectoBin(n,v);
for(i=0; i<10; i++){
printf("%d",v[i]);
}
return 0;
}
I tried with your program, too, but yours prints numbers that i can't understand.
#include<stdio.h>
#include<math.h>
int i,n,v[11],p;
void DecToBin(int n, int v[11]){
for(i=10; i<0; i--){
p=pow(2,i);
printf("%d\n",p);
if((n&p)!=0){
v[10-i]++;
}
}
}
int main(){
int digits[11];
printf("Inserisci il numero decimale da convertire: ");
scanf("%d",&n);
DecToBin(n,digits);
printf("Il numero in binario es ");
for (i=0; i<10; i++){
printf("%d",digits[i]);
}
printf("\n");