关于C#中数字转换的算法混淆

Algorithm confusion regarding the number conversion in C#

我正在学习有关在 C# 中将整数转换为等效口语的教程。

我对三位数规则有点困惑。

// Single-digit and small number names
private static string[] smallNumbers = new string[]
  {
    "zero", "one", "two", "three", "four", "five", "six", "seven", "eight",
    "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen",
    "sixteen", "seventeen", "eighteen", "nineteen"
  };

// Tens number names from twenty upwards
private static string[] tens = new string[]
  {
    "", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy",
    "eighty", "ninety"
  };

// Scale number names for use during recombination
private static string[] scaleNumbers = new string[]
  {
    "", "thousand", "million", "billion", "trillion",
    "quadrillion", "quintillion"
  };

public static string ToWords(this BigInteger number)
{
  
  if (number == 0)
  {
    return "zero";
  }

  
  int[] digitGroups = new int[groups];

  // Ensure a positive number to extract from
  var positive = BigInteger.Abs(number);

  // Extract the three-digit groups
  for (int i = 0; i < groups; i++)
  {
    digitGroups[i] = (int)(positive % 1000);
    positive /= 1000;
  }

  //The rest of the code.. 
}

我假设现在我们正在转换一个数字,它的值为 25111。

for-loop function中,(int)(positive % 1000)的return值应该是111。111不匹配digitalGroups数组中的任何元素。

我不太明白,谁能给我解释一下?提前致谢。

您向我们展示的代码不匹配,而是将值 111 分配给了 digitGroupsArray 的第一项。

digitGroupsArray 有多少项?我不知道,这取决于 'groups' 变量值,我们在代码摘录中看不到。

这里:

int[] digitGroups = new int[groups];

您正在创建一个名为 digitGroups 的新空整数数组,其长度为 (int) 'group' 值。

同时,

 for (int i = 0; i < groups; i++)
 {
     digitGroups[i] = (int)(positive % 1000);
     positive /= 1000;
 }

是一个循环,一次迭代。请注意,每次 'positive' 变量除以 1000(如 positive = positive / 1000)。

结果会是这样的:

digitGroups[0] = (int)(25111 % 1000) // first item of digitGroupsarray
'positive' gets divided (25111 / 1000) next time will be 25
digitGroups[1] = (int)(25 % 1000) // second item of digitGroupsarray
'positive' gets divided again (25 / 1000) next time will be 0

等等...

在这些情况下,记录值和调试循环非常常见和有用。它真的让你头脑清醒。

工作示例:

static void Main(string[] args)
    {
        int groups = 3;
        int[] digitGroups = new int[groups];
        int positive = 25111;

        for (int x = 0; x < groups; x++)
        {
            Console.WriteLine("positive value is: " + positive);
            digitGroups[x] = (int)(positive % 1000);
            positive /= 1000;
            Console.WriteLine("item number (index): " + x + " value: " + digitGroups[x]);
        }
    }

输出:

positive value is: 25111
item number (index): 0 value: 111
positive value is: 25
item number (index): 1 value: 25
positive value is: 0
item number (index): 2 value: 0