hi i just done my program and the input have some digits gone from it.i don't know how to recorrect it so i will like to seek advice here please

#include <iostream>
#include <cmath>

using namespace std;

void convert(int , int, int, int*); //convert(number, base, length, result)

int len=0, i;

int main()
{
int num, base, *r;

cout<<"\nEnter a number: ";
cin>>num;
cout<<"\nEnter base: ";
cin>>base;

len=(int)log10(num)/log10(base)+1; //Number of digits of the converted number

r=new int [len];

convert(num, base, len, r);

cout<<endl;

for(i=0; i<len; i++)
cout<<*(r+i);

delete [] r;

return 0;
}

void convert(int n, int b, int len, int* res)
{
for(i=0; i<len; i++)
{
*(res+len-i-1)=n%b;
n/=b;
}
}

the output is so wrong.
for example i inputed digit 89 and spec.base number 2.
the real answer is supposed to be 1011001 but i go only 1001!!
how to be the correct ones??same with other bases.all outputs have less digits then required..

Recommended Answers

All 2 Replies

When posting c++ code, please use c++ code tags
[code=c++] // Your code here

[/code]

In the line:

len=(int)log10(num)/log10(base)+1;

the (int) is binding to the log10 call
rewrite the line as follows to get the logs divided before taking the int:

len = (int)(log10((double)num)/log10((double)base))+1;

The casts to double are in there because my compiler (vc++ express) was complaining that it couldn't figure out which overload to use.

thanks for it.any idea how to make this code more efficient?
it looks in a mess to me.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.