You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修复这段C语言二进制转十进制代码?排查代码失效原因

Binary to Decimal Conversion: Fixing Your Code Issues

Let's break down what's going wrong in your code and fix it step by step. Your suspicion about pointer and character-integer multiplication issues is correct—those are part of the problem, but there are a few other logic bugs too.

Key Issues in Your Current Code

  • Pointer Comparison & Traversal Error: In while(*t!="\0"), you're comparing a char (*t) to a string literal ("\0"), which is a pointer address. This comparison will never be true, leading to an infinite loop. You need to use the character literal '\0' instead. Also, you never increment t in the loop, so it stays stuck on the first character forever.
  • Incorrect scanf Argument: scanf("%s",&cara); is wrong because cara is already a pointer to the start of the array. Using &cara passes a pointer to the array itself (type char (*)[100]), which doesn't match %s's requirement of a char*. Just use scanf("%s", cara);.
  • Character-to-Integer Mismatch: When you do cara[i]*pow(2,m), cara[i] is a character like '1' (ASCII value 49) or '0' (ASCII value 48). You need to convert it to its integer equivalent first by subtracting '0' (e.g., cara[i] - '0').
  • Floating-Point Precision with pow: The pow function returns a double, which can have precision errors (e.g., pow(2,3) might be 7.999999999 instead of 8). Using integer arithmetic to calculate powers of 2 is safer here.
  • Unnecessary Array Modification & Off-by-One Error: You're modifying the original cara array with calculated values, which is unnecessary. Plus, in your final sum loop, you're using cara[i] where i is already equal to j (out of bounds)—you should be using cara[k].

Fixed Code

Here's the corrected version with explanations in comments:

#include <stdio.h>
// No need for math.h now since we'll calculate powers with integer arithmetic

int main() {
    char cara[100];
    int sum = 0;
    int length = 0;

    printf("Enter a binary number\n");
    // cara is already a pointer, no need for &
    scanf("%s", cara);

    // First, calculate the length of the binary string
    char *t = cara;
    while (*t != '\0') {
        length++;
        t++; // Move the pointer to the next character
    }

    // Convert each bit to decimal and accumulate the sum
    for (int i = 0; i < length; i++) {
        // Convert character to integer (e.g., '1' -> 1, '0' -> 0)
        int bit = cara[i] - '0';
        // Calculate 2^(length - 1 - i) using left shift (equivalent to 2^power)
        int power = 1 << (length - 1 - i);
        sum += bit * power;
    }

    printf("Decimal equivalent: %d\n", sum);
    return 0;
}

Alternative Simplified Version

You can even combine the length calculation and conversion into a single loop to make it more efficient—this leverages how binary to decimal conversion works naturally:

#include <stdio.h>

int main() {
    char cara[100];
    int sum = 0;

    printf("Enter a binary number\n");
    scanf("%s", cara);

    char *t = cara;
    while (*t != '\0') {
        // Shift sum left by 1 (equivalent to multiplying by 2)
        sum = sum * 2;
        // Add the current bit's integer value
        sum += (*t - '0');
        t++;
    }

    printf("Decimal equivalent: %d\n", sum);
    return 0;
}

For example, converting "101" with this method: ((0*2)+1)*2+0)*2+1 = 5—it's a more intuitive way to build the decimal value as you iterate through the binary string.

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 09:02:30