/*
* 冒泡
*/
Console.WriteLine("[冒泡");
int[] aa = [1, 3, 8, 4, 2, 5, 7, 6];
maopao(aa);
void maopao(int[] a)
{
for (int i = 0; i < a.Length; i++)
{
for (int j = 0; j < i; j++)
{
if (a[i] > a[j]) //大于则是降序,小于则是升序
{
int b = a[i];
a[i] = a[j];
a[j] = b;
}
}
}
Console.WriteLine(string.Join(',', a));
}
/*
* 递归计算阶乘
*/
Console.WriteLine("计算阶乘");
int n = 0;
if (n >= 0)
{
Console.WriteLine(digui(n));
}
int digui(int b)
{
if (b == 0 || b==1)
{
return 1;
}
else
{
return b * digui(b - 1);
}
}
/*
* 斐波那契 1,1,2,3,5,8,13
*/
Console.WriteLine("斐波那契");
fib(10);
//输出前十个
void fib(int n)
{
int fib1 = 1;
int fib2 = 1;
int fib;
for (int i = 0; i < n; i++)
{
if (i < 2)
{
Console.Write($"{fib1} ");//前两项为1
continue;
}
fib = fib1 + fib2; //前两项相加得第三项
Console.Write($"{fib} ");
//更新前面两项,为下一次计算做准备
fib1 = fib2;
fib2 = fib;
}
Console.WriteLine();
}
C#冒泡,递归,计算斐波那契数列
最新推荐文章于 2024-09-02 19:43:41 发布