C语言生成1到n的二进制数:错误程序排查与正确实现解析
First: Why Your Initial Program Was Outputting Wrong Results
Your first code has a clear logic issue in the binary_number function—you're not storing all the binary digits, only the last one you calculate, then repeating it. Let's break down what's happening:
- In
binary_number(int n):- You initialize
bin_n = 0andi = 0. - The while loop calculates
n % 2(the current least significant bit) and stores it inbin_n, then updatesnton/2. But you're overwritingbin_nevery loop—so by the end of the loop,bin_nonly holds the last bit (which is always 1 for any positive n, since odd numbers end with 1, even numbers eventually reduce to 1). - Then your for loop runs
itimes, printingbin_neach time. That's why you get strings of 1s (e.g., input 5 gives 111, input 2 gives 11)—you're just printing the last bit multiple times.
- You initialize
Here's the problematic snippet highlighted:
void binary_number(int n) { int bin_n = 0; int i = 0; while (n > 0) { bin_n = n % 2; // Overwrites bin_n every time, only keeps the last bit n = n / 2; i++; } for (int j = i - 1; j >= 0; j--) printf("%d", bin_n, j); // Prints the same bit i times printf("\n"); }
A quick fix for this function would be to collect the bits in a variable (like the correct program does) or print them as you calculate them (you'd need to reverse the order, though).
Second: How the Correct Program Works
Let's walk through the correct code line by line to understand its logic:
#include <stdio.h> int main() { int n,i=0,bin=0,plc,dig=0,j; printf("Enter the n value : "); scanf("%d",&n); printf("\nBinary numbers from 1 to %d : ",n); for(i=0;i<=n;i++) { // Loop through every number from 0 to n plc=0;bin=0;dig=0; // Reset variables for each new number for(plc=1,j=i;j>0;j=j/2) { // Convert current i to binary dig=j%2; // Get the least significant bit of j bin=bin+(dig*plc); // Add this bit to bin at the correct position plc=plc*10; // Shift "position" left (multiply by 10 to move to next digit) } printf("%d\n",bin); // Print the binary number (stored as a decimal integer) } }
Let's use i=5 as an example to see the inner loop in action:
- Start with
plc=1,j=5:dig=5%2=1(the rightmost bit of 5 is 1)bin=0 + (1*1)=1(store this bit in the "ones place" of bin)plc=1*10=10(next bit will go in the tens place)
j=5/2=2:dig=2%2=0(next bit is 0)bin=1 + (0*10)=1(add 0 to the tens place)plc=10*10=100(next bit goes in hundreds place)
j=2/2=1:dig=1%2=1(next bit is 1)bin=1 + (1*100)=101(add 1 to the hundreds place)plc=100*10=1000
j=1/2=0: loop exits, print101
This method builds the binary number as a decimal integer (e.g., binary 101 is stored as the decimal number 101) by shifting the position multiplier (plc) by 10 each time, effectively placing each bit in the correct digit position.
内容的提问来源于stack exchange,提问作者Noobprotagonistprogrammer

