C言語関係掲示板

過去ログ

No.304.C++で10進数をn進数にかえる関数

[戻る] [ホームページ]

No.1821

C++で
投稿者---enmaru(2002/06/26 15:35:30)


10進数をn進数にかえる関数のプログラムをおしえてくさい

No.1825

Re:C++で
投稿者---かずま(2002/06/26 19:01:11)


>10進数をn進数にかえる関数のプログラムをおしえてくさい

ここは、C言語の掲示板ですよ。なぜ「C++で」なんですか。おしえて「くさい」
でも、おもしろいから、解のひとつを示しましょう。
#include <iostream>
#include <string>
using namespace std;

string decimal_to_base_n(unsigned int x, unsigned int n)
{
    string s;
    if (x >= n) s = decimal_to_base_n(x / n, n);
    return s + "0123456789abcdefghijklmnopqrstuvwxyz"[x % n];
}
    
int main()
{
    unsigned int x, n;

    while (cin >> x >> n && n >= 2 && n <= 36)
        cout << decimal_to_base_n(x, n) << endl;
    return 0;
}