0

トレーニング サイトで数値を 2 進数に分解するために何かをコーディングしています。ローカル コンパイラで何百回もテストしましたが、問題なく動作しますが、トレーニング サイトでエラーがあることがわかりました。

(私のコードはエレガントでも効率的でもありません。特にループですが、コードを分解してエラーの可能性がある場所を理解しました)。エラーがあるかどうか誰か教えてもらえますか?

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


//function that displays the greatest power of 2 less than a fixed number N
int residu(int N)

{
    int i;
    int M=2;
    for(i=0;i<N;i++){
        if(M>N){break;}else{M=2*M;i++;}
    }
    return M/2;
}


int main()
{
    int i;

    //N is the input to decompose
    int N;
    scanf("%d",&N);
    //We will search for the greatest power of 2 less than a fixed number N, 
    //than repeating the some process with the residue of N with the greatest power of 2        //less than N, so we have to store the value of N for the loop (see below) we will use to work //correctly
    int M;
    M=N;
    //D displays the diffrence betwenn two successive powers of 2 that appears in the    //binary decomposition, (we will then print "O")
    int D;
    D=log(residu(N))/log(2);

        for(i=0;i<M;i++){
            //If N==residu(N), the decomposition is finished
            if(N==residu(N)){printf("1");int k;
                for(k=0;k<D;k++){printf("0");}break;}
            else{
             // N is a the residue of the former value of N and the greatest power of 2 //less than N
                N=N-residu(N);
                D=D-log(residu(N))/log(2);
                printf("1");
                int k;
                for(k=0;k<D-1;k++){printf("0");
                }
                D=log(residu(N))/log(2);
            }        
    }
}
4

4 に答える 4

5

これは、浮動小数点計算の典型的な問題です。この関数logはフロートで動作します。

log(8) / log(2)は として計算され、 に変換されるときに に2.999...切り捨てられます。2int

そのため、間違った結果が得られます。正確な動作はコンパイラ/マシンに依存します。詳細については、Goldbergなどを参照してください。

一般に、整数と浮動小数点の計算をそのように混在させることは悪い考えです。関数residuは、正確な 2 進対数を報告する必要があります。または、次のような整数の対数を計算するための専用関数を実装します

unsigned binlog(unsigned n) {
    unsigned i = 0;
    while (n > 1) { n /= 2; ++i; }
    return i;
}
于 2012-09-07T11:24:43.007 に答える
1

すでに述べたように、数学ライブラリのインクルードがありません:

#include <math.h>

また、このプログラムは入力「0」では動作しないというエラーがあります。

于 2012-09-07T11:03:50.087 に答える
1

数学ライブラリを含める必要があります

#include <math.h>
于 2012-09-07T10:51:37.100 に答える
0

次の修正を試してください。

1) ログ関数の math.h をインクルードします。

#include <math.h>

2) 各関数の先頭 (または各関数内の各スコープの先頭) ですべての変数を宣言します。

int main() {  
int i;      
//N is the input to decompose
int N;
int M;
//D displays the diffrence betwenn two successive powers of 2 that appears in the
//binary decomposition, (we will then print "O") 
int D;
...
if(N==residu(N)){int k;printf("1");
...
else{  
   int k; 

3) メインから何かを返します。戻り値の型が「int」なので、

return 0;

4) それでもうまくいかない場合は、これらのステートメントの戻り値を明示的に型キャストしてみてください。

D=log(residu(N))/log(2);
D=D-log(residu(N))/log(2);
D=log(residu(N))/log(2);

double の結果を取得して int に格納すると、データが失われるという警告がスローされます。

于 2012-09-07T11:12:26.757 に答える