I am having trouble figuring out how to convert base 10 to base 3, I have tried several different attempts and this is my latest effort, anyone have any ideas.
I was giving this algorithm but am having trouble creating a function for it:
1. Set k to the number of digits needed in the converted number(k = floor(logb(v)+ 1) or (floor(10(v)/log10( b )+1)
2. Print digit (v/(b^(k-1)) most significant remaining digit
3. set v to v%(b^(k-1)) the remaining part of the base 10 digit
4. subtract 1 from k(reduce the power on the base by 1)
Implementation position = position/base
#include <iostream>
#include <cmath>
#include <iomanip>
#include <fstream>
using namespace std;
int convert_base(int v, int b);
ifstream inputdata;
int main(int argc, char *argv[]){
int a, b, c, d, e, f, i;
int base = 3;
int count = 6;
inputdata.open("Base_Conversion_File.dat");
if(!inputdata){
cout << "There was a problem opening the data file." << endl;
return 1;
}
inputdata >> a >> b >> c >> d >> e >> f;
cout << a << "\t" << b << "\t" << c << "\t"
<< d << "\t" << e << "\t" << f << endl;
for(i = 0; i <= count; i++){
if(i == 0){
cout << a << " converted to base 3 is:\t" << convert_base(a, base) << endl;
}
else if(i == 1){
cout << b << " converted to base 3 is:\t" << convert_base(b, base) << endl;
}
else if(i == 2){
cout << c << " converted to base 3 is:\t" << convert_base(c, base) << endl;
}
else if(i == 3){
cout << d << " converted to base 3 is:\t" << convert_base(d, base) << endl;
}
else if(i == 4){
cout << e << " converted to base 3 is:\t" << convert_base(e, base) << endl;
}
else if(i == 5){
cout << f << " converted to base 3 is:\t" << convert_base(f, base) << endl;
}
}
return 0;
}
int convert_base(int v, int b){
int k, i, convert;
k = floor(log10(v)/log10(b)) + 1;
cout << (int)(v/ pow(b, k-1));
v = v % pow(b, k-1);
return k;
}