【问题标题】:Do we need to subtract Convert.ToInt32(o) with 48 every time? When there is a need to minus and when its not?我们每次都需要用 48 减去 Convert.ToInt32(o) 吗?什么时候需要减,什么时候不需要?
【发布时间】:2017-01-02 19:06:47
【问题描述】:
int num = Convert.ToInt32(Console.ReadLine());

通过上面的代码,我得到了正确的整数值,并且能够对这个数字进行运算并得到正确的结果。

但是使用下面的代码,为什么 Convert.ToInt32(o) 方法没有将其转换为整数值。为什么我们需要减去 48。

int[] numarr = number.ToString().Select(o => Convert.ToInt32(o)-48).ToArray();

如果我不减去 48,我就没有得到正确的整数值。

请谁能解释这是为什么?每次都需要做吗?因为我在其他地方计算的结果没有减去 48,我得到了正确的结果。

我正在做一个程序来打印一个数字中出现的次数。 这是我的代码:

Console.WriteLine("Enter the number:");
int number = Convert.ToInt32(Console.ReadLine());

Console.WriteLine("Enter the number to search:");
int searchnumber = Convert.ToInt32(Console.ReadLine());
int cnt = 0;

int[] numarr = number.ToString().Select(o => Convert.ToInt32(o)-48).ToArray();
for (int i = 0; i < numarr.Length; i++)
{
    Console.WriteLine(numarr[i]);
}
for (int i = 0; i < numarr.Length; i++)
{
    if (numarr[i] == searchnumber)
    {
        cnt++;
    }
}

Console.WriteLine("Number of occurence of given number is:{0}", cnt);

【问题讨论】:

  • 您到底想完成什么?举个例子说明“number”和“o”是什么。
  • @AsheraH- 我解释了。

标签: c# ascii


【解决方案1】:

因为您将数字转换为字符串,所以您检索的整数实际上是字符串中字符的 Unicode 代码点。根据 ASCII 码表,0 字符从位置 48 开始。

所以您实际上找到了一种将字符转换为整数表示的解决方法。如果您只是想以一种不那么老套的方式获取数字,您可以使用this answer,它使用模数运算符。或者 char.ToNumericValue 在您的原始字符串上,正如 Time Schmelter 在评论中建议的那样。

【讨论】:

  • 使用char.GetNBumericValue: int[] numarr = number.ToString().Select(c =&gt; (int)char.GetNumericValue(c)).ToArray();
  • @TimSchmelter 转换为字符串以再次转换回数字感觉很糟糕。
  • Int to BCD 会更好更快,即使它不是一行
  • @SurabhiPandey:仅当您想将 char 转换为 int 时。如果是字符串,则不需要它
  • 字符本身与转换为整数的字符串不同。字符实际上是变相的整数,指向码表中的位置而不是'实际'的整数值。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-09-16
  • 2019-07-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-09-21
相关资源
最近更新 更多