c++ - 数字系统转换器不适用于特定编译器 (Dev-C++)

标签 c++ c converters

选项 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/

相关文章:

c - 我正在使用dstev计算特征向量得到零值

c - 查找已知的整数键集

C#:有没有简单的方法可以将字符串转换为 RTF?

excel - 如何在 Excel 中将带有 "subscript"分数的数字转换为小数?

c++ - 在函数 findx() 中是否有替代 const_cast<char*> 的方法?

c++ - Visual C++ 测试开箱即用项目中的错误

c++ - 使 Clang-Format 忽略换行符的注释

c - sort 函数不会打印排序后的数组?

java - java中的编码转换

c++ - 如何专门化模板类中的模板成员函数?