#include <iostream>
usingnamespace std;
string to_base (int number,int base)
{
string bases = "0123456789ABCDEF";
string result = " ";
do{
result = bases[ number%base ]+result;
number = number/base;
}while(number>0);
return result;
}
int main(){
int a,b,ok;
do{
do{
cout<<"Enter a natural number ";
cin>>a;
}while(a<=0);
do{
cout<<"enter a base to which convert the given number(2-16): ";
cin>>b;
}while ((b<2)||(b>16));
cout<<"number "<<a<<" in base "<<b<<" is: "<<to_base(a,b)<<endl;
cout<<"Do you want to continue(1) or finish(0)?"<<endl;
cin>>ok;
}while(ok==1);
return 0;
}
But unfourtunately my JavaScript code for the same program gives me a result of something like: 001010101010111011
Why is that?
Any help will be gladly appreciated.
<script>
function to_base(number, base) {
bases = "01234566789ABCDEF";
result = "";
do {
result = bases.charAt(number % base) +result ;
number = number/base;
} while (number > 0);
return result;
}
do{
do{
var a = Number(prompt("Enter a natural number: "," "));
}while(a<=0);
do{
var b = Number(prompt("Enter a base to which convert(2-16): "," "));
}while((b<2)||(b>16));
var texxt = "number " + a +" base " + b + " is " +to_base(a,b);
window.alert(texxt);
var ok = Number(prompt("Do you want to continue(1) or finish (0)?" , " "));
}while(ok==1);
</script>
That's why you get a lot of zeroes, because none of these decimals are exactly zero.
To fix this you need to encapsulate number/base in Math.floor()
1 2 3 4 5 6 7 8 9
function to_base(number, base) {
bases = "01234566789ABCDEF";
result = "";
do {
result = bases.charAt(number % base) +result ;
number = Math.floor(number/base);
} while (number > 0);
return result;
}
I admit my code in my past post was not quite correct but you need to bear in mind this is a C++ forum, not for JavaScript.