我正在關注一個關于將整數轉換為 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)應該是 111。111 不匹配digitalGroups陣列中的任何元素。
不是很明白,誰能給我解釋一下?提前致謝。
uj5u.com熱心網友回復:
您向我們展示的代碼不匹配,而是將值 111 分配給 digitGroupsArray 的第一項。
digitGroupsArray 有多少項?我不知道,這取決于“組”變數值,我們在代碼摘錄中看不到。
這里:
int[] digitGroups = new int[groups];
您正在創建一個名為 digitGroups 的新空整數陣列,其長度為 (int) 'group' 值。
而這,
for (int i = 0; i < groups; i )
{
digitGroups[i] = (int)(positive % 1000);
positive /= 1000;
}
是一個周期,一個迭代。請注意,每次“正”變數除以 1000(如正 = 正 / 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
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/417842.html
標籤:
上一篇:通過Kestrel(不是IISExpress)托管的VisualStudio中的BlazorServer是否支持在Razor檔案更改時自動重建?
