【问题标题】:Is there a way to store INT and strings in the same array?有没有办法将 INT 和字符串存储在同一个数组中?
【发布时间】:2019-11-17 16:27:23
【问题描述】:

我不确定解析是如何工作的,我也无法在 C++ 中完成。

我创建了一个将十进制转换为十六进制的算法。该算法现在仍然输出大于 9 的值,例如 10 而不是 A。下面的函数应该可以解决这个问题,但是当我运行它时,我无法将正常的 1-9 值与 As 和 Bs 存储在同一个数组中,这意味着我无法输出它们。我已经坚持了 2 天。

string hexValues(int remainder)
{
    string A = "A";
    string B = "B";
    string C = "C";
    string D = "D";
    string E = "E";
    string F = "F";

    if (remainder == 10)
    {
        return A;
    }
    else if (remainder == 11)
    {
        return B;
    }
    else if (remainder == 12)
    {
        return C;
    }
    else if (remainder == 13)
    {
        return D;
    }
    else if (remainder == 14)
    {
        return E;
    }
    else if (remainder == 15)
    {
        return F;
    }
}
 hexMod = userDecNumber4Hex % 16;
            if (hexMod > 9)
            {
                hexadecimalAnswer[y] = hexValues(hexMod);
            }
            else
            {
                hexadecimalAnswer[y] = hexMod;
            }


    while (userDecNumber4Hex != 0)
    {
        if (userDecNumber4Hex % 16 != 0)
        {
            hexMod = userDecNumber4Hex % 16;
            if (hexMod > 9)
            {
                hexadecimalAnswer[y] = hexValues(hexMod);
            }
            else
            {
                hexadecimalAnswer[y] = hexMod;
            }

            userDecNumber4Hex = (userDecNumber4Hex-hexMod)/ 16;
            y += 1;
        }
        else if (userDecNumber4Hex % 16 == 0)
        {
            userDecNumber4Hex = userDecNumber4Hex / 16; 
            if (userDecNumber4Hex > 9)
            {
                hexadecimalAnswer[y] = userDecNumber4Hex;
            }

        }

    }

代码很长,所以我不确定要发布什么,但有多个数组——但它只是其中一个我需要存储从 hexValues 函数获得的值,而它已经有 int 值

【问题讨论】:

  • 这与“将 int 和字符串存储在同一个数组中”无关,尽管 C++17 有一个可以用来执行此操作的模板。例如,如果您的“余数”是 3,则只需返回“3”。这就是转换为十六进制的工作原理。如果你想要一个包含 16 个值的数组,它只是一个 std::strings 的数组:{"0","1",'2","3","4","5","6","7","8","9","A","B","C","D","E","F"}
  • 您的代码中没有数组。

标签: c++ hex


【解决方案1】:

由于您的十六进制数字中的整数仅介于09 之间,因此您可以将它们存储为字符。同时,您也可以将A-F 存储为字符。 因此,改为将字符作为面值返回。

char hexValues (int remainder)
{
    if (remainder < 10)
        return '0' + remainder;
    else 
        return 'A' + (remainder - 10);
}

为了完全转换,这是使用递归的好借口:

string decToHex (int n)
{
     if (n < 16)
     {
         string s (1, decToHex (n));
         return s;
     }
     else 
         return decToHex (n / 16) + hexValues (n % 16);
}

【讨论】:

  • 我无法上传图片,但输出现在只是一个带有小问号的小盒子。
  • @Teddles 你确定remainder 介于0-15 之间吗?
  • 是的!如果我删除“hexValues”函数并正常运行算法,它仍然会将小数转换为十六进制,但不是 1A,它会写 110- 我当然知道是 1 和 10,但它看起来像 110
  • 我很乐意,但我不确定我是否会因此受到老师的惩罚,我不想冒险失败,但我可以向您展示处理的算法十六进制。
  • 我可能弄错了,但这似乎不像它会处理不是 16 的因数的数字。不过我不确定
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多