选项 3(十进制到二进制) 它适用于 Code:Blocks 具体而言,尚未在 Visual C++ 上尝试过,但我们学校使用 Dev-C++,我无法弄清楚是什么原因导致了问题。我的意思是它在逻辑上和句法上都是正确的。
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#define MAXDIGITS 100
void printmenu(void);
void getchoice(void);
void decitobinary(int str);
int main(void)
{
char choice;
printmenu();
getchoice();
system("cls");
while(1)
{
printf("\nAgain? y/n: ");
scanf("\n%c",&choice);
if(choice == 'y' || choice == 'Y')
{
system("cls");
main();
}
else if(choice == 'n' || choice == 'N')
exit(EXIT_SUCCESS);
else
{
printf("\a\nInvalid input.\n");
continue;
}
}
}
void printmenu(void)
{
printf("\n3 - Decimal -> Binary");
printf("\n19 - Exit Program\n");
}
void getchoice(void)
{
int choice;
char number[MAXDIGITS];
int digits;
printf("\nEnter choice: ");
scanf("\n%d",&choice);
switch(choice)
{
case 3:
{
system("cls");
printf("Enter number: ");
scanf("\n%d",&digits);
decitobinary(digits);
break;
}
case 19:
exit(EXIT_SUCCESS);
}
}
void decitobinary(int str)
{
int arraycntr = 0;
int number[arraycntr];
printf("\n%d in binary is: ",str);
while(str > 0)
{
number[arraycntr] = str % 2;
str /= 2;
++arraycntr;
}
for(arraycntr -= 1;arraycntr >= 0;arraycntr--)
{
printf("%d",number[arraycntr]);
}
printf("\n");
system("pause");
}
最佳答案
void decitobinary(int str)
{
int arraycntr = 0;
int number[arraycntr];
printf("\n%d in binary is: ",str);
while(str > 0)
{
number[arraycntr] = str % 2;
str /= 2;
++arraycntr;
}
for(arraycntr -= 1;arraycntr >= 0;arraycntr--)
{
printf("%d",number[arraycntr]);
}
printf("\n");
system("pause");
}
问题出在 number 数组的初始化中。它应该是这样的:
int number[33];
33位足以存储所有二进制数字。
关于c++ - 数字系统转换器不适用于特定编译器 (Dev-C++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11356269/