所以我对C还是很陌生,十进制到二进制的转换遇到了麻烦。
我正在尝试转换2个数字-“ 205”和“ 171”太二进制,并将它们都放在单独的数组中,以及它们的工作方式。看到它们都正确地转换,但是它们都尾随三个额外的“ 1”。
例如,当我使用“ printf”来查看x数组中的内容时,它是“ 11001101111”而不是“ 11001101”。 y数组也是如此。
到目前为止,这里是程序(我试图对其进行注释以使其尽可能清晰)。
注意:我已注释掉y数组的“ printf”,但您可以根据需要将其切换出来。
int inputx = 205;
int inputy = 171;
//scanf("%d %d", &inputx, &inputy); //
int x[16] = {};
int y[16] = {};
//declaring variables for x conversion
int i = 0;
int d1 = 0;
int c = 0;
int a = 0;
int number1[16] = {};
//converting inputx from decimal into binary
while (inputx != 0){
i = i+1;
d1 = inputx % 2;
inputx = inputx / 2;
c++;
number1[c]=d1;
}//end while
//since the binary array is in reverse, this loop fixes it
for(a = 0; a < c; a = a + 1 ){
x[a]=number1[c-a];
printf("%d", x[a]); //printf just for testing
}//end for
//declaring variables for y conversion
i = 0;
d1 = 0;
int c2 = 0;
a = 0;
int number2[16] = {};
//converting inputy from decimal to binary
while (inputy != 0){
i = i+1;
d1 = inputy % 2;
inputy = inputy / 2;
c2++;
number2[c2]=d1;
}//end while
//since the binary array is in reverse, this loop fixes it
for(a = 0; a < c2; a = a + 1 ){
y[a] = number2[c2-a];
// printf("%d", y[a]); //printf just for testing
}//end for
感谢您的帮助!