我尝试使用以下代码将一个数字从基数10转换为另一个基数。如果目标基数中没有零(0),它就会起作用。检查79和3,并正确打印2221。现在尝试19和3,结果将是21而不是201,这表示出了问题。
int x, y, a = 0, i, t, j;
cout << "enter two numbers" << endl;
cin >> x >> y; // x as the number in base-10 and x, as the destination base
a = x;
while (x >= y)
{
t = 1;
for (i = 0; x > y; i++)
{
x /= y;
}
cout << x;
for (j = 0; j < i; j++)
{
t *= y;
}
a = a - (t*x);
x = a;
}
cout << x<<endl;发布于 2014-10-22 03:13:49
对于您要完成的任务,使用递归函数比使用while循环更容易。
这是工作程序。
#include <iostream>
void printInBase(int x, int y)
{
if ( x < y )
{
std::cout << x;
return;
}
int rem = x%y;
printInBase(x/y, y);
std::cout << rem;
}
int main()
{
int x, y;
std::cout << "enter two numbers" << std::endl;
std::cin >> x >> y; // x as the number in base-10 and x, as the destination base
printInBase(x, y);
std::cout << '\n';
}发布于 2014-10-22 03:02:44
int x, y, a = 0, i, t, j;
cout << "enter two numbers" << endl;
cin >> x >> y; // x as the number in base-10 and x, as the destination base
a = x;
t = 1;
while (x >= t*y)
{
t = t * y;
}
while (t)
{
cout << x/t << ' ';
x -= t*(x/t);
t /= y;
}
cout << '\n';基本上,您没有跟踪您打印的是哪个数字,并且您的代码无法判断何时需要前导零。你可以通过打印像2*(3^2) + 1*(3^0)这样的东西或者像我在上面的代码中那样提前计算出需要多少位数来解决这个问题。
发布于 2014-10-22 03:11:50
尽管它可以工作,但这种方法在概念上是错误的:您本质上混淆了数字(算术运算的主题)和它们的文本表示(用于表示它们的数字序列)。
类型int -by一个外部视点-没有“基数”(整数很可能有一个基数-2的内部表示,这对于算术单元电路操作的目的是起作用的):它只是一个被加,减,多乘,除,异或等的东西。
当您执行<<所做的cout << a时,是将a数字转换为表示它的数字序列,从而使其具有可读性。默认情况下,它恰好以10为基数的数字表示为ASCII字符('0'...'9')。
您要做的是将一个数字转换为另一个数字,该数字的十进制表示形式与您要映射的基数相似。它可以在打印中工作,但没有算法可以与它一起工作。因此,int不是它们的正确表示。
您需要的是一个不同的文本转换器:它接受一个int和另一个指定基数的int,并输出代表您的数字的字符。
对像这样的类思考
class based
{
int n, base;
public:
based(int num, int base) :n(num), base(base) {}
friend std::ostream& operator<<(std::ostream& out, const based& x);
};将用作
std::cout << bsed(79,3) << ' ' << based(19,3) << std::endl;现在
std::ostream& operator<<(std::ostream& out, const based& x)
{
static const size_t N = 8*sizeof(int)+2; //base 2 is the widest, and is 32 or 64 + 2
char buff[N]; //keep space for sign + base2 + terminator
size_t X = N-1; //current writing character position
buff[X] = 0; //terminating char
--X; //prepare next left character
int n = x.n; //we will work on n
bool neg = (n<0); //keep negative sign
if(neg) n=-n; //and work always with posiotives
while(n) //we will reduce n down to 0
{
int digit = n%x.base; //mod is the last digit
n /= x.base; //next to the left
buff[X] = (digit<10)? char(digit+'0'): char(digit-10+'A');
--X; //next char
}
if(neg) buff[X] = '-';
else ++X; //no sign
out << buff+X << '(' << x.base << ')'; //the text from the point we reach towards left
return out;
}这将输出2221(3) 201(3)。
还有一种更便携的方式来做char(digit+'0')等,但考虑到正常的数字,这并不是更多所需的。
https://stackoverflow.com/questions/26493701
复制相似问题