C#基础知识总结(七)

摘要

  C#最简单的两个算法:输入数字打印出菱形星星、冒泡排序
1.输入数字打印出菱形星星

static void Main(string[] args)
{
    //输入一个数,表示菱形星号,数字必须是一个正奇数
    int number = 0;
    do
    {
        Console.WriteLine("请输入一个正奇数:");
        try
        {
            number = Convert.ToInt32(Console.ReadLine());
        }
        catch
        {
            //Console.WriteLine("请输入一个正奇数:");
        }
    } while (number <= 0 || number % 2 == 0);

    for (int i = 0; i < number; i++)
    {
        //下面两行计算星星个数是重点
        int starCount = 1 + ( i > number / 2 ? number - i - 1 : i ) * 2;
        int emptyCount = ( number - starCount ) /2;
        for (int j = 0; j < emptyCount; j++)
        {
            Console.Write(" ");
        }
        for (int k = 0; k < starCount; k++)
        {
            Console.Write("*");
        }
        Console.WriteLine("");
    }
    
    Console.ReadKey();
}

2.冒泡排序

int[] scores = {3,1,2,4};

for(int i= 0; i < scores.Length -1; i++)
{
    for(int j = 0;j = scores.Length - i - 1; j++)
    {
        if(scores[j] < scores[j+1])
        {
            int temp = scores[j];
            scores[j] = scores[j+1];
            scores[j+1] = temp;
        }
    }
}

 

posted @ 2018-11-30 23:52  Liar。  阅读(286)  评论(0编辑  收藏  举报