有很多问题,但我似乎无法在答案中找到原因。通常是:不,用这个替换它,否则这应该可以工作。
我的任务是创建一个程序,要求用户输入一个 3 位正整数(十进制),将其转换为八进制。
例如,在纸上:将数字 112 转换为八进制。(8 是八进制的基数。)
这些是您将采取的步骤:
余数自下而上是八进制数,十进制表示112。所以 112 的八进制数是 160。
我在互联网上找到了以下程序,但我不完全理解。节目中的评论是我的。有人可以向我解释一下吗?
//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();
Run Code Online (Sandbox Code Playgroud)
任何帮助都非常感谢。
首先要理解的是:这是解决这个问题的可怕方法。代码充满了奇怪的选择;看起来有人对这个问题采用了一个糟糕的 C 解决方案并将其转换为 C#,而没有仔细考虑或使用良好的实践。如果你想学习如何理解你在互联网上发现的蹩脚代码,这是一个很好的例子。如果您正在尝试学习如何设计好的代码,这是一个很好的例子,说明不应该做什么。
//declaration and initialization of variables but why is there an array?
Run Code Online (Sandbox Code Playgroud)
有一个数组是因为我们希望存储所有的八进制数字,而数组是一种用于存储多个相同类型数据的便捷机制。
但我们可以在这里提出一些更相关的问题:
i- 显然是数组的当前索引 - 从 1 开始?!这简直太奇怪了。数组在 C# 中从零开始。然后我们继续:
decimalNumber = int.Parse(Console.ReadLine());
Run Code Online (Sandbox Code Playgroud)
此代码假定输入的文本是合法整数,但不能保证。所以这个程序可能会崩溃。 TryParse应使用,并应处理故障模式。
// 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;
Run Code Online (Sandbox Code Playgroud)
代码的作者认为他们很聪明。这太聪明了。将脑海中的代码重写为最初应该如何实现。首先,重命名i为currentIndex. 接下来,每个语句产生一个副作用,而不是两个:
while (quotient != 0)
{
octalNumber[currentIndex] = quotient % 8;
currentIndex += 1;
quotient = quotient / 8;
}
Run Code Online (Sandbox Code Playgroud)
现在应该清楚发生了什么。
// I don't understand the code below here as well.
for (j = i - 1; j > 0; j--)
Console.Write(octalNumber[j]);
Run Code Online (Sandbox Code Playgroud)
做一个小例子。假设数字是 14,也就是八进制的 16。第一次循环时,我们将 6 放入槽 1。下一次,我们将 1 放入槽 2。所以数组是{0, 6, 1, 0, 0, 0, 0 ... }并且i是 3。我们希望输出16。所以我们将 j 从 i-1 循环到 1,然后打印出 1 然后是 6。
因此,为您练习: 再次编写此程序,这次使用设计良好的 C# 程序的约定。将您的尝试放在代码审查站点上,人们会很乐意为您提供有关如何改进它的提示。