使用oops概念打印从1到1000的数字
本文关键字:1000 数字 oops 打印 使用 | 更新日期: 2023-09-27 18:06:14
如何使用oop概念(即不使用循环,数组和递归)打印从1到1000的数字
既然您提到了OOP概念,其中之一就是封装。当方法完成工作时,你不关心实现细节。
几乎所有的linq扩展方法在实现中都使用了循环(实际上不同于迭代器),很容易没有意识到这一点,因为它是封装在实现中的细节。
要回答你的问题,不使用循环的唯一方法是编写WriteLine调用1000次。
在OOP中,您创建一个类来封装逻辑,然后使用它:
class Program
{
static void Main(string[] args)
{
(new RangePrinter).PrintRange(1, 1001);
}
}
没有循环,对吗?实际上,循环被封装在实现中。
class RangePrinter
{
/* Injecting the Write target is skipped for simplicity */
public void PrintRange(int lowerBound, int upperBound)
{
for(int i = lowerBound; i < upperBound; i++)
{
Console.WriteLine(i);
}
}
}
同样适用于使用Enumerable(又名Linq扩展方法):
Enumerable.Range(1, 1000).ToList().ForEach(x=> { Console.WriteLine(x); });
下面是。net框架团队如何实现Range Internal方法的:
static IEnumerable<int> RangeIterator(int start, int count) {
for (int i = 0; i < count; i++) yield return start + i;
}
结论,当你需要做重复的工作时,你需要一个循环。任何在集合上迭代的c# API (Linq的Where, Select等)都使用循环。循环并不坏,除非不需要它们,或者当有其他方法时它们被嵌套。
只是为了好玩,如果这是一个谜题(忘记OOP需求部分),那么您可以这样做:
string oneToThousand = @"1'r'n2'r'n3'r'n4'r'n5'r'n6'r'n7'r'n8'r'n9'r'n10'r'n11'r'n12'r'n13'r'n14'r'n15'r'n16'r'n17'r'n18'r'n19'r'n20'r'n" +
"21'r'n22'r'n23'r'n24'r'n25'r'n26'r'n27'r'n28'r'n29'r'n30'r'n31'r'n32'r'n33'r'n34'r'n35'r'n36'r'n37'r'n38'r'n39'r'n40'r'n" +
"41'r'n42'r'n43'r'n44'r'n45'r'n46'r'n47'r'n48'r'n49'r'n50'r'n51'r'n52'r'n53'r'n54'r'n55'r'n56'r'n57'r'n58'r'n59'r'n60'r'n" +
"61'r'n62'r'n63'r'n64'r'n65'r'n66'r'n67'r'n68'r'n69'r'n70'r'n71'r'n72'r'n73'r'n74'r'n75'r'n76'r'n77'r'n78'r'n79'r'n80'r'n" +
"81'r'n82'r'n83'r'n84'r'n85'r'n86'r'n87'r'n88'r'n89'r'n90'r'n91'r'n92'r'n93'r'n94'r'n95'r'n96'r'n97'r'n98'r'n99'r'n100'r'n";
/* Continue to 1000 */
Console.WriteLine(oneToThousand);
递归函数(DEF)是一种函数,它要么调用自己,要么处于函数调用的潜在循环中。正如定义所指定的,有两种类型的递归函数。考虑一个调用自身的函数:我们称这种类型的递归为直接递归。
例子:
public static void PrintTo(int number)
{
if (number == 0)
return;
Console.WriteLine(number);
PrintTo(number - 1);
}
static void Main(string[] args)
{
PrintTo(1000);
}