C中变量值的改变

时间:2018-01-28 08:59:41

标签: c

[更新]:Keine Lust的答案,明确声明数组的大小解决了这个问题。

我正在尝试在C中编写我自己的十进制到二进制转换器(在下面发布),由于名为a的变量值的更改,它不断地给出错误的输出。为什么改变发生?我使用的编译器是gcc。

#include <stdio.h>
#include <string.h>
#include <math.h>
int main(void) {
 int j = 0; // This variable is used to counter the iterations of while-loop
 int a; // This variable holds user-input
 char b[] = {}; // This is character array to hold the value of bits after operation
 printf("Enter a number to convert into binary\n>>>");
 scanf("%d", &a); 
 while(a!=0){ // Loop until the value of a is 0
  printf("a before modulus: %d \n", a); // printing a for debugging
  int bit = a % 2; // represents binary digit
  printf("a after modulus:%d \n", a); // print a for debugging
  switch(bit){ // switch-case to identify the bit
   case 1:
    b[j] = '1'; 
    break;
   case 0:
    b[j] = '0';
    break; 
  }
    printf("a after switch-case:%d \n", a); // the value of a is altered after switch-case, check output.
    a = (int) floor((float)(a/2));  
    j += 1;
 }
printf("\n");
  return 0; 
}

输出:(输入:2)

a before modulus:2

后模数:2

后切换案例:48

a before modulus:24

后模量:24

后切换案例:12312

a before modulus:6156

后模数:6156

.....继续

已完成的完整代码: [更新]

    #include <stdio.h>
    #include <string.h>
    #include <math.h>
    int main(void) {
    const int MAX_SIZE = sizeof(char) * 10000; // Will hold 10000 characters
        int j = 0; // This variable is used to counter the iterations of while-loop
        int a,temp; // This variable holds user-input
        char b[MAX_SIZE]; // This is character array to hold the value of bits after operation will hol
        printf("Enter a number to convert into binary\n>>>");
        scanf("%d", &a);
        temp = a; 
        int bits = log(a)/log(2);
        bits += 1;
        while(a!=0){ // Loop until the value of a is 0

          int bit = a % 2; // represents binary digit

       switch(bit){ // switch-case to identify the bit
        case 1:
            b[j] = '1'; 
            break;
        case 0:
            b[j] = '0';
            break; 
       }
            a = a/2;    
            j += 1;
      }
        printf("The %d in binary is: ",temp);
      for (int c=(bits-1);c>=0;c--) {
        printf("%c", b[c]); 
      }
        printf("\n");
       return 0; 
     }

0 个答案:

没有答案
相关问题