为什么在16号基座时输出不正确

时间:2014-10-29 05:26:24

标签: c++ base

我要编写一个程序,允许我将任何数字转换为任何数字。

我的节目目前输出" 1669"当正确输出为16E时,对于366 base 16。我的代码搞砸了哪里?

#include <iostream>
using namespace std;

int main()
{
    int iInter, iBase, iRemainder, i, iMax;
    int rgiTable[25];
    char cAgain;

    do
    {
        do
        {
            cout << "Enter an integer greater than zero" << endl;
            cin >> iInter;

            cout << "Enter a base between the numbers 2 and 16" << endl;
            cin >> iBase;

            if (iInter < 0)
                cout << "Enter a new Integer" << endl;
            if (iBase < 2 || iBase > 16)
                cout<< "Enter a new base" << endl;
        } while (iInter < 0 || (iBase < 2 || iBase > 16));

        for (i = 0; iInter > 0; i++)
        {
            iRemainder = iInter % iBase;
            iInter = iInter / iBase;

            if (iRemainder == 0)
                rgiTable[i] = 0;
            if (iRemainder == 1)
                rgiTable[i] = 1;
            if (iRemainder == 2)
                rgiTable[i] = 2;
            if (iRemainder == 3)
                rgiTable[i] = 3;
            if (iRemainder == 4)
                rgiTable[i] = 4;
            if (iRemainder == 5)
                rgiTable[i] = 5;
            if (iRemainder == 6)
                rgiTable[i] = 6;
            if (iRemainder == 7)
                rgiTable[i] = 7;
            if (iRemainder == 8)
                rgiTable[i] = 8;
            if (iRemainder == 9)
                rgiTable[i] = 9;
            if (iRemainder == 10)
                rgiTable[i] = 'A';
            if (iRemainder == 11)
                rgiTable[i] = 'B';
            if (iRemainder == 12)
                rgiTable[i] = 'C';
            if (iRemainder == 13)
                rgiTable[i] = 'D';
            if (iRemainder == 14)
                rgiTable[i] = 'E';
            if (iRemainder == 15)
                rgiTable[i] = 'F';

            iMax = i;
        }

        while (iMax >= 0)
        {
            cout << rgiTable[iMax];
            iMax--;
        }
        cout << endl;

        cout << "Do you wish to enter more data? y/n" << endl;
        cin >> cAgain;

    } while (cAgain == 'y'|| cAgain == 'Y');

    return 0;
}

2 个答案:

答案 0 :(得分:2)

使用

打印数字时
cout<< rgiTable[iMax];

您正在打印整数。当该整数值等于E时,您将获得E的ASCII值,即69。

而不是

int rgiTable [25];

你应该使用

char rgiTable [25];

while循环中,使用字符'0' - '9'代替数字0 - 9

您可以使用以下方法简化逻辑:

  for ( i=0; iInter > 0; i++)
  {
     iRemainder = iInter % iBase;
     iInter = iInter / iBase;

     if ( iRemainder < 10 )
     {
        rgiTable [i] = iRemainder + '0';
     }
     else 
     {
        rgiTable [i] = iRemainder + 'A' - 10;
     }

     iMax = i;
  }

答案 1 :(得分:1)

大写E字符的ASCII code是69.你必须决定数组rgiTable是否应该存储整数0到16或ASCII码&#39; 0&#39;通过&#39; E&#39;。如果决定后一种设计,可以将其声明为char rgiTable[25],以确保在输出到cout时数组元素的格式正确。

顺便说一下,初始化所有局部变量是个好主意。在这种情况下,当iInter为0时,您有一个错误:永远不会初始化iMax,因此程序会输出垃圾数据。