-1
The exercise asks a program to read a binary number in the form of a 'char' vector from the keyboard and return its corresponding to base 10. I wrote a code but the values it returns are wrong, someone can tell me why?
#include <stdio.h>
int main(){
int expon(int a, int x){
int i, um;
um = 1;
for(i=0; i<x;i++){
um = um * a;
};
return um;
}
char number[1024];
scanf("%s", number);
int i;
int n = strlen(number) - 1;
int novo = 0;
for(i=0; i<n+1; i++){
novo = novo + (number[i] * expon(2, n-i));
}
printf("%d", novo);
}
Also, I think a few tips on how to make my code more readable wouldn’t go amiss
There’s something very wrong there. You’re declaring a function within the
main()
. Look, I recommend one more time because I’m missing basic knowledge so it’s hard to help.– Shinforinpola
In addition to what Shinforinpola said note that number is a char vector but in your account you do not want to treat the numerical representation of the characters but the value 0 or 1 (the character '0' corresponds to decimal 48). Do: new += ((number[i] - '0') * expon(2, n-i));
– anonimo
Use #include <string. h> for strlen to be used and in principle it will work
– White
Possible duplicate of How to convert binary to decimal?
– Leandro Paiva