I have to write a program in C that will take a base b
from the user (assuming b is between 2 and 10), a natural number n
and then n
numbers that represent the digits of some number m
in base b
. The program should print out what decimal number m
was input. For example, if you put b=5
and n=4
and then the numbers 3
,4
, 2
and 1
the program should output 486
because m=3*5^3+4*5^2+2*5^1+1*5^0=486
Note: You can assume that the digits will be the numbers between 0
and b-1
.
So here's what I've done:
#include<stdio.h>
#include<math.h>
int main(void) {
int x,n,b,k=0,num=0,i,j;
scanf("%d", &b);
scanf("%d", &n);
for(i=1; i<=n; i++) {
scanf("%d", &x);
for(j=1; j<b; j++){
if(j>k){
num=num+x*(pow(b,n-j));
k=j;
break;
}
}
}
printf("m=%d", num);
return 0;
}
Can you tell me why this doesn't work for the numbers given in the example above? It outputs 485
instead of 486
, while if I take for example b=7, n=3
and then numbers 5, 6
and 1
, I get the correct solution m=288
.
I suggest checking the return value of
scanf()
, Something like this is the right idea:Input:
Output: