I’m trying to reverse the numbers input by user (i.e. numbers input by user are stored in an array as long as he inputs a positive number ).
However, when I input
123 4569 752 896 -1
the output is
321 9653 257 698
As you can see the second number is not 9654. I couldn’t fix it.
#include <stdio.h>
#include <math.h>
// finding the number of digits
int bsm(int a){
int i=0;
while(a!=0){
i++;
a=a/10;
}
return i;
}
// reversing the number
int rev(int m,int a){
int s=0,sum=0;
while(a!=0){
s=a%10;
sum+=s*pow(10,m)/10;
m--;
a=a/10;
}
return sum;
}
int main()
{
int i=0,k,a[10],p,r;
scanf("%d",&a[i]);
while(a[i]>0){
i++;
scanf("%d",&a[i]);
}
for(k=0;k<i;k++){
p=bsm(a[k]);
r=rev(p,a[k]);
printf("\n%d ",r);
}
return 0;
}
Since this looks like homework, I’ll limit my answer to two hints.
When you use
pow(), it returns a floating-point number, and floating-point numbers are inexact. Rewrite your program using only integer maths or strings.Think about how you wish to handle numbers that end in zeroes; for example, what should be the reverse of 2000?