【发布时间】:2018-01-26 05:55:04
【问题描述】:
有很多问题,但我似乎无法在答案中找到原因。通常是:不,用这个替换它,否则它应该可以工作。
我的任务是创建一个程序,要求用户输入一个 3 位正整数(十进制),然后将其转换为八进制。
例如,在纸上:将数字 112 转换为八进制。 (8 是八进制的基数。)
这些是您将采取的步骤:
- 112 / 8 = 14 余数 = 0
- 14 / 8 = 1 余数 = 6
- 1 / 8 = 0 余数 = 1
余数从下到上是八进制数,十进制表示 112。 所以 112 的八进制数是 160。
我在互联网上找到了以下程序,但我不完全理解。 程序中的cmets是我的。谁能给我解释一下?
//declaration and initialization of variables but why is there an array?
int decimalNumber, quotient, i = 1, j;
int[] octalNumber = new int[100];
//input
Console.WriteLine("Enter a Decimal Number :");
decimalNumber = int.Parse(Console.ReadLine());
quotient = decimalNumber;
//as long as quotient is not equal to 0, statement will run
while (quotient != 0)
{
//this is how the remainder is calculated but it is then put in an array + 1, i don't understand this.
octalNumber[i++] = quotient % 8;
//divide the number given by the user with the octal base number
quotient = quotient / 8;
}
Console.Write("Equivalent Octal Number is ");
//i don't understand the code below here aswell.
for (j = i - 1; j > 0; j--)
Console.Write(octalNumber[j]);
Console.Read();
非常感谢任何帮助。
【问题讨论】:
-
Convert.ToString(decimalNumber, 8)不够好吗? -
有一个数组,因为每个八进制数字都存储在一个位置。最后,存储在数组中的数字以相反的顺序写入控制台。