Storing the different digits of a number into an array of int.

Hello :)

The aim is : If i have a natural number [max 5 digits] (say) n=13579. Then a[4]=1, a[3]=3, a[2]=5. a[1]=7. a[0]=9.
I start with a[4]= n/10000 .. then n= n - a[4]*10000;
then a[3]= n/1000. .. n= n - a[3]*1000;
i.e a[i]= n/10^i .... n= n - a[i]*10^i;

To reduce code size i used a for loop.
The code is free from any syntax errors.
Its the "output" that is weird. I enter 13579 and what the program process is:
a[4]=1 a[3]=3 a[2]=5 a[1]=8 a[0]=5

Same goes for other numbers too.. leaving the most significant digit , the rest digits are just out of the logic!!

I want to now if i went wrong somewhere or is it hardware or software bug!
I am using CodeBlocks 12.11 and compiler is GNU GCC compiler.

Here is the output window:
http://postimg.org/image/nea3qm29r/

Here is the code:

#include<iostream>
#include<math.h>
using namespace std;
int main()
{
int n,a[5],i,t,dec,divisor; // n: storing number; t: copy of n,
// divisor for 10000/1000/...
//dec How much to subtract from no. to get rid of Most significant digit
// i for running for loop; a[5] the array for storing digits

cout<<" Enter the number ( <10000 ): ";
cin>>n;

t=n;

for(i=4;i>=0;i--)
{
cout<<"\n t = "<<t<<" i = "<<i;

divisor=pow(10,i);
a[i]= t/divisor;

cout<<" a["<<i<<"] = "<<a[i] <<" t = " <<t<<" ";

dec=a[i]*divisor;
cout<<"dec = "<<dec;

t = t-dec;
cout<<" "<<t;
}

return 0;
}
Man!! I am amused.
I had spent 3 hours whacking my head over this. After writing the above post. A sudden thought of replacing pow() came to my mind.

I just replaced pow() by a "for loop" to evaluate the divisor.

divisor=1;
for(j=1;j<=i;j++)
divisor=divisor*10;

And the program is working like Charm!! No bugs anymore.. Correct output for any input number!

Can anyone please tell me why replacing pow() removed the bug ?
the pow function returns a double not an integer
http://www.cplusplus.com/reference/cmath/pow/
Last edited on
Topic archived. No new replies allowed.