2012-09-07 22 views
0

我正在编写一些东西在训练网站上分解二进制数字。我已经在我的本地编译器上测试过一百次了,它工作得很好,但是培训网站告诉我有错误。 (我的代码既不优雅也不高效,特别是循环,但是我分解了代码以理解错误的可能性)。有谁能告诉我是否有错误?C中的二进制分解

#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); 
      }   
    } 
} 
+0

祈祷告诉 - 这些错误是什么? –

+0

有什么错误? – Flavio

+0

培训网站并没有告诉你任何比“只有错误”更具体的内容吗? –

回答

5

这是一个浮点计算的典型问题。功能log与浮游物一起使用。

log(8)/log(2)正在计算为2.999...,然后在将其转换为int时截断为2

这就是为什么你会得到错误的结果。确切的行为是编译器/机器相关的。有关更多阅读,请参阅Goldberg

以这种方式混合整数和浮点计算通常是一个坏主意。您的功能residu应报告确切的二进制对数。或者你执行一个专门的函数来计算登录整数,类似于

unsigned binlog(unsigned n) { 
    unsigned i = 0; 
    while (n > 1) { n /= 2; ++i; } 
    return i; 
} 
+0

非常感谢,它工作正常。我选择第二种选择。但是,什么是精确的二进制对数?是否可以使用本机日志功能? – user1611830

+1

“原生”的'log'函数(你应该使用'log2' btw。)计算一个接近对数的float值(不是精确的)。既然你需要2的幂的二进制记录的确切值,'log'不适合。使用整数算术可以计算基数幂的精确对数(不是近似值)。 –

1

您需要包括数学库

#include <math.h> 
1

如前所述你缺少了包括数学库:

#include <math.h> 

而且,在这个程序中的错误将不适用于输入“0”。

+0

是的事实上,我加了这个奇特的情况,但我不想让我编辑的代码太大 – user1611830

0

尝试使用以下修正:

1)包括用于将日志功能

#include <math.h> 

2)声明所有变量在每个功能的顶部(或在每个范围的内顶部math.h中每个功能),即:

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)从main中返回一些东西。它的返回类型“INT”,以便添加

return 0; 

4)如果仍然无法做到这一点,你可以尝试显式类型转换这些语句的回报:

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

他们扔了警告关于数据丢失的结果是双重结果并将其存储在int中。

+0

谢谢我要去试试 – user1611830

+1

关于项目2:自1999年以来,您可以在C中混合使用声明和声明(尽管某些人认为这是不好的做法)。这当然不是这里的问题。 –

+0

@undur_gongor - 我们(至少我)不知道“培训网站”使用什么编译器,也不知道它的选项。 gcc可以,但是如果你使用MS 2010 Express,那么在操作之后,它实际上会弹出声明。 因为我们没有什么问题的细节,所以最好是安全,然后抱歉。 – Mike