You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

如何用递归函数实现十进制转二进制?含错误代码修正方案

Fixing the Decimal to Binary Conversion Code

Let's break down the problems in your original code and solve them step by step:

1. Why the Original Output Was Garbage

Your base2 and remainder variables were uninitialized when you first printed them. In C, uninitialized variables hold random garbage values, which caused the first line of output to be incorrect. Additionally, your loop didn't collect the remainders to build the final binary string, and it wasn't using recursion as required.

2. Corrected Recursive Implementation

Here's a modular solution that splits the logic into functions, fixes the output, and generates the correct binary result:

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

// Prints each step of the decimal-to-binary division
void printConversionSteps(int n) {
    if (n == 0) {
        return;
    }
    int quotient = n / 2;
    int remainder = n % 2;
    printf("%d / 2 = %d, remainder %d\n", n, quotient, remainder);
    printConversionSteps(quotient);
}

// Recursively converts decimal to binary and returns the result as a string
char* convertToBinary(int n) {
    // Base cases
    if (n == 0) {
        char* result = malloc(2 * sizeof(char));
        strcpy(result, "0");
        return result;
    }
    if (n == 1) {
        char* result = malloc(2 * sizeof(char));
        strcpy(result, "1");
        return result;
    }
    
    int remainder = n % 2;
    char* subBinary = convertToBinary(n / 2);
    
    // Allocate memory for the full binary string
    int subLength = strlen(subBinary);
    char* result = malloc((subLength + 2) * sizeof(char));
    
    // Append the current remainder to the sub-binary string
    strcpy(result, subBinary);
    result[subLength] = '0' + remainder;
    result[subLength + 1] = '\0';
    
    free(subBinary); // Clean up allocated memory
    return result;
}

// Prints the final conversion result line
void printBinaryResult(int decimal, char* binary) {
    printf("%d (base10) = %s (base2)\n", decimal, binary);
}

int main() {
    int base10 = 710;
    
    // Print the division steps
    printConversionSteps(base10);
    
    // Convert to binary
    char* base2 = convertToBinary(base10);
    
    // Print the final result
    printBinaryResult(base10, base2);
    
    // Free the allocated string to avoid memory leaks
    free(base2);
    
    return 0;
}

3. Key Improvements Explained

  • Fixed Garbage Output: The printConversionSteps function computes the quotient and remainder before printing each line, eliminating uninitialized variable issues.
  • Recursive Structure: Both printConversionSteps and convertToBinary use recursion to follow the decimal-to-binary process correctly.
  • Modular Functions: The code is split into three focused functions:
    • printConversionSteps: Handles printing each division step.
    • convertToBinary: Recursively builds the binary string (using dynamic memory allocation to handle variable-length results).
    • printBinaryResult: Formats and prints the final conversion line.
  • Correct Binary String: The convertToBinary function builds the binary string in the correct order by appending each remainder to the result of the recursive call (which handles the higher bits).

4. Expected Output

When you run this code, you'll get:

710 / 2 = 355, remainder 0
355 / 2 = 177, remainder 1
177 / 2 = 88, remainder 1
88 / 2 = 44, remainder 0
44 / 2 = 22, remainder 0
22 / 2 = 11, remainder 0
11 / 2 = 5, remainder 1
5 / 2 = 2, remainder 1
2 / 2 = 1, remainder 0
1 / 2 = 0, remainder 1
710 (base10) = 1011000110 (base2)

Which matches the expected output you provided.

内容的提问来源于stack exchange,提问作者jaycodez

火山引擎 最新活动