0

g-adic拡張をc++言語でプログラムしたいのですが、何を試しても出力が間違っています。まず、g-adic展開とは何かを説明しましょう。g-adic展開は、数値を表す方法です。たとえば、2進数の場合、これは数値の2進法の展開です。そして、16進数は16進展開です。だからここに私のコードがあります:

#include <iostream>
#include <cmath>
#include <complex>
#include <valarray>

using namespace std;

int main()
{
    int x;
    int g;
    cin>>x;
    cin>>g;
    int k=log(x)/log(g)+1;
    int e;
    int b=0;
    int* myArray=NULL;
    myArray=new int[k];

    for(int i=0;i<k;i++)
    {
        myArray[i]=0;
    }

    while(b!=k)
    {
        e=x/(g^(k-b-1));
        myArray[b]=e;
        x=x-e*g^(k-b-1);
        b++;
    }

    b=0;

    while(b!=k)
    {
        cout<<myArray[b]<<endl;
        b++;
    }

    delete [] myArray;
    myArray=NULL;

    return 0;
}

たとえば、105を2進数に変換する場合、x=105およびg=2の場合、kは新しい数値の長さです。この場合、それは7です。inte = 105/2 ^(7-1)=1。これが最初の番号です。次に、x = 105-1 * 2 ^(7-1)=41です。これを手動で行うと、105が1101001になることがわかります。しかし、このコードをコンパイルすると、機能しません。私の質問は、このコードの何が問題になっているのかということです。

4

2 に答える 2

0

here: run this program

#include <iostream.h>
#include <cmath>
#include<stdlib.h>
#include<stdio.h>

int main()
{
    int x;
    int g;
    cin>>x;
    cin>>g;

    while(x>g)
    {
        cout<<x%g<<endl;
        x/=g;
    }
            cout<<x%g<<endl;

    return 0;
    }

works for 105 and 2 and does not need an array

于 2012-07-18T14:55:57.320 に答える
0

The ^ doesn't do exponentiation. It's the exclusive-or operator. To do exponentiation, use the pow function.

e=x/std::pow(double(g),double(k-b-1));
myArray[b]=e;
x=x-e*std::pow(double(g),double(k-b-1));

You can see your program in action, with my changes, on IDE One.

于 2012-07-18T15:37:15.693 に答える