1、用两个线程一个输出字母一个输出数字,交替输出Chat数组
char[] aI = "1234567".ToCharArray();
char[] aC = "ABCDEFG".ToCharArray();
Task task1 = null;
Task task2 = null;
task1 = Task.Run(() =>
{
foreach (var item in aI)
{
Console.WriteLine(item);
task1.Wait(100);
}
});
task2 = Task.Run(() =>
{
foreach (var item in aC)
{
Console.WriteLine(item);
task2.Wait(100);
}
});
Task.WaitAll(task1, task2);
Console.ReadLine();
2、用C#代码获取文件夹里及子文件夹所有文件名
static void Main(string[] args)
{
string filePath = @"E:\笔记";
string[] strs = Directory.GetFiles(filePath, "*", SearchOption.AllDirectories);
foreach (var item in strs)
{
Console.WriteLine(item);
}
}
3、二分查找
//二分查找
public static int Erfen(int[] ints, int target)
{
int left = 0, right = ints.Length - 1;
while(left < right)
{
int mid = left + (right - left) / 2;
if (ints[mid] == target)
{
return mid;
}else if (ints[mid] < target)
{
left = mid + 1;
}
else
{
right = mid - 1;
}
}
return -1;
}
4、斐波那契数列
using System.Collections;
using System.Text.Json;
namespace Test1
{
internal class Program
{
static void Main(string[] args)
{
Console.WriteLine("Feibo1");
Console.WriteLine(Feibo1(1));
Console.WriteLine(Feibo1(2));
Console.WriteLine(Feibo1(3));
Console.WriteLine(Feibo1(4));
Console.WriteLine(Feibo1(5));
Console.WriteLine("Feibo2");
Console.WriteLine(Feibo2(1));
Console.WriteLine(Feibo2(2));
Console.WriteLine(Feibo2(3));
Console.WriteLine(Feibo2(4));
Console.WriteLine(Feibo2(5));
Console.WriteLine("Feibo3");
foreach (var item in Feibo3().Take(10))
{
Console.WriteLine(item);//斐波那契数列
}
}
//递归
public static int Feibo1(int n)
{
if (n == 1)
{
return 0;
}
if (n == 2 || n == 3) { return 1; }
if (n > 3)
{
return Feibo1(n-2)+Feibo1(n-1);
}
return 0;
}
//迭代循环
public static int Feibo2(int n)
{
if (n == 1)
{
return 0;
}
if (n == 2) { return 1; }
int first = 0, second = 1, next = 0;
for (int i = 3; i <= n; i++)
{
next = first + second;
first = second;
second = next;
}
return next;
}
//
public static IEnumerable<int> Feibo3()
{
var (x, y) = (0, 1);
yield return x;
yield return y;
while (true)
{
(x, y) = (y, x + y);
yield return y;
}
}
}
}