0

我在使用递归将字母添加到 base 10 - base 12 转换时遇到问题。我将如何在我的函数中添加字母?我正在考虑在其中添加一个 if 语句,但我不知道在哪里以及如何去做。感谢指点谢谢!

给定从 1 到 12 的计数:

Dec 1 2 3 4 5 6 7 8 9 10 11 12 

Duo 1 2 3 4 5 6 7 8 9 X  E  10

我的功能:

template<class myType>
myType convertDec(myType number){
    if(number == 0)
        return number;
    //if statement somewhere in here? not sure considering i can't touch the return statement
    return (number % 12) + 10*convertDec(number / 12);
}

理想输出示例:

65280 = 31940 (工作正常)

2147483626 = 4EE23088X (不起作用!)

4

2 回答 2

6
#include <iostream>
#include <string>

using namespace std;

string ConvertToDuodecimal(unsigned long long n)
{
  if (n < 12)
    return string() + "0123456789XE"[n];
  return ConvertToDuodecimal(n / 12) + ConvertToDuodecimal(n % 12);
}

int main()
{
  cout << ConvertToDuodecimal(0) << endl;
  cout << ConvertToDuodecimal(1) << endl;
  cout << ConvertToDuodecimal(10) << endl;
  cout << ConvertToDuodecimal(11) << endl;
  cout << ConvertToDuodecimal(12) << endl;
  cout << ConvertToDuodecimal(13) << endl;
  cout << ConvertToDuodecimal(65280) << endl;
  cout << ConvertToDuodecimal(2147483626) << endl;
  return 0;
}

输出(ideone):

0
1
X
E
10
11
31940
4EE23088X
于 2013-04-09T17:49:19.760 回答
0

基数是数字显示方式的属性,与它的内部表示无关。您需要编写一个使用基数 12 打印普通 int 的函数。

a = 12;         // A = 12 (in base 10)
printf("%d",a); // Prints a in base 10 (still 12)
printf("%x",a); // Prints a in base 16 (now C)

您的代码正在更改实际值,这不是正确的做法。

(是的,在书呆子罢工之前, printf 不是好的 C++ ......)

于 2013-04-09T17:48:23.130 回答