如何修复这段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 achar(*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 incrementtin the loop, so it stays stuck on the first character forever. - Incorrect
scanfArgument:scanf("%s",&cara);is wrong becausecarais already a pointer to the start of the array. Using&carapasses a pointer to the array itself (typechar (*)[100]), which doesn't match%s's requirement of achar*. Just usescanf("%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: Thepowfunction returns adouble, which can have precision errors (e.g.,pow(2,3)might be7.999999999instead of8). Using integer arithmetic to calculate powers of 2 is safer here. - Unnecessary Array Modification & Off-by-One Error: You're modifying the original
caraarray with calculated values, which is unnecessary. Plus, in your final sum loop, you're usingcara[i]whereiis already equal toj(out of bounds)—you should be usingcara[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
相关产品推荐
相关产品推荐

