For some reason the program is not working when I try to run it and I can't figure it out. I'd appricate any help. Homework stuff, so I have to stick to the very basics.
#include <stdio.h>
long long int decimal(long long int);
int power_2 (int);
long int power_10 (int);
int main(void){
long long int n;
while(1){
printf("Write down a binary number. \n");
scanf("%lld", &n);
long long int a = decimal(n);
printf("The binary number %lld converted into decimal is: %lld \n", n, a);
}
}
//Here what I realized is if let's say I have the number 1001, then I subtract 1 and divide by 10, the remainder is going to be 0, meaning it will "jump" on the second if statement. I don't really know how to solve it.
long long int decimal(long long int e){
long long int result;
long long int k = 0;
int i;
for(i=0; i>=0; i ){
if(e % 10 == 1){
k = power_2(i);
e--;
if(e != 0){
e /= 10;
}
}
if(e % 10 == 0){
e /= 10;
if(e==0){
break;
}
}
return(k);
}
//This function should work, so it's not a problem
int power_2(int n){
int base = 2, i, result = 1;
if(n>0){
for(i=1; i<=n; i ){
result *= base;
}
}
if(n=0){
result = 1;
}
return(result);
}
//This is just something I thought I would need but no
long int power_10(int n){
int base = 10, i, result = 1;
if(n>0){
for(i=1; i<=n; i ){
result *= base;
}
}
if(n=0){
result = 1;
}
return(result);
}
CodePudding user response:
You can't use scanf
with %lld
to input a binary number string (e.g. 10101010101010101010101010101010101
). It will interpret the number incorrectly.
You have to accept it as a char
string (e.g).
char str[100];
scanf("%s",str);
But, scanf
is problematic because it can overflow str
. And, IMO, the "usual" remedy of:
scanf("