我在 C 中的二进制到十进制方法的无限循环错误?

Infinite loop error with my binary to decimal method in C?

我的方法出现无限循环,我不确定为什么。我正在研究一种假设将位从十进制转换为二进制形式的方法。我看不到发生了什么,因为当我 运行 这个方法时我得到了一个无限循环。我希望我能得到一些帮助。

这是我的代码:

int binToDec(char* bin)
{       
        int i = 0;

        int result = 0; // (1) start the decimal result at 0.   
        while(bin != "\n");// (2) remove the most significant binary digit(leftmost) and add it to the result.
        {

        if(bin[i] == '1')
        {       
                result = result * 2 + 1;
        }
        else if(bin[i] == '0')
        {       
                result *= 2;
        } 
        printf("%d\n", result);
        i++;    
        }       // (3) If all binary digits have been removed, you're done. Stop.
                // (4) Otherwise, multiply the result by 2 and go back to step 2.
        return result;
}
/**
 * Create two functions that do binary to decimal conversion and back. Their signatures (aka prototypes)
 * should look like:
 * int binToDec(char* bin);
 * char* decToBin(int dec);
 *
 * For both functions, remember that your string will not hold 0s and 1s, but the characters ‘0’ and ‘1’. 
 * Use the offset to determine the binary value.      
 */
    char* decToBin(int dec)
{

        int i;
        double z;
        for(i = 0; i < dec; i++)
        {
                 z = pow(2, i);
                printf("The bit is %d \n", z);
        }
        char *c = (char*) malloc(dec * sizeof(z));

        while(dec % 2 != 0) //As long as the quotient is not 0, continue to divide the newest quotient by 2.
        {
                c[i] +=  dec % 2 + '0';
                dec = dec / 2; //Divide the value by 2 and record the remainder.        
        i++;
        }
        return c;
}
int main()
{
        int num;
        char *ptr;
        ptr = (char*) malloc(num * sizeof(decToBin(11001)));

        printf("Call to binToDec given 1001 result in: %d\n", binToDec("11001"));
        printf("Call to decToBin given 9 results in : %s\n", decToBin(11001));
        free(ptr);
        return 0;
}

告诉我。无限循环发生在第一个方法中。

这个循环

while(bin != "\n");
                 ^^^ 

确实是一个无限循环,因为字符串文字“\n”在大多数情况下与指针bin指向的字符串文字具有不同的地址。而且就算写

while( "\n" != "\n");

那么循环也可以是无限的,因为编译器(取决于它的选项)可以将相同的字符串文字存储为不同的对象。

此声明

ptr = (char*) malloc(num * sizeof(decToBin(11001)));

没有意义,因为没有使用指针 ptr 并且没有初始化变量 num。

和这个声明

char *c = (char*) malloc(dec * sizeof(z));

没有意义。比如为什么要用sizeof( double )(变量z的类型是double)?并且函数返回的字符串不是零终止的。

也在这些通话中

printf("Call to binToDec given 1001 result in: %d\n", binToDec("11001"));
                               ^^^^                             ^^^^^

printf("Call to decToBin given 9 results in : %s\n", decToBin(11001));
                              ^^^                             ^^^^^

有错别字。

看来你的意思如下

#include <stdio.h>

unsigned int binToDec( const char *bin )
{       
        unsigned int result = 0; // (1) start the decimal result at 0.   

        for ( ; *bin != '[=15=]'; ++bin ) // (2) remove the most significant binary digit(leftmost) and add it to the result.
        {
            result = 2 * result + ( *bin == '1' );
        }       // (3) If all binary digits have been removed, you're done. Stop.
                // (4) Otherwise, multiply the result by 2 and go back to step 2.

        return result;
}

int main(void) 
{
    const char *bin = "11001";

    printf( "Call to binToDec given %s result in: %u\n", bin, binToDec( bin ) );

    return 0;
}

程序输出为

Call to binToDec given 11001 result in: 25

看看这一行:

while(bin != "\n");

即使 ; 不存在,条件也永远不会变为真,只是因为您不能那样比较字符串。必须是

while( strcmp(bin, "\n") != 0 )

但是看看显然应该是循环体的内容,您不会增加指针 bin 而是一个整数 i。所以最后,你的条件应该是

while( strcmp(bin+i, "\n") != 0)

或者干脆

while( bin[i] != '\n' )

...并且没有 `;'当然

正如@barmar 正确提到的那样,如果您使用根本不包含换行符的字符串调用 binToDec(),您仍然有一个无限循环。所以因为 bin 应该只包含 '0''1',我建议:

  while( bin[i] == '0' || bin[i] == '1' ) 

或者,如果你想支持 'formatted' 二进制字符串(例如,每 8 位数字后有一个 space)

  while( bin[i] != '[=15=]' && bin[i] != '\n' ) 

如果 bin[i] 既不是 '0' 也不是 '1'

,那么你的循环体就已经很好了,因为你什么都不做