C#基础知识总结(七)

时间:2022-06-20 20:03:50

摘要

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

static void Main(string[] args)
{
//输入一个数,表示菱形星号,数字必须是一个正奇数
int number = ;
do
{
Console.WriteLine("请输入一个正奇数:");
try
{
number = Convert.ToInt32(Console.ReadLine());
}
catch
{
//Console.WriteLine("请输入一个正奇数:");
}
} while (number <= || number % == ); for (int i = ; i < number; i++)
{
//下面两行计算星星个数是重点
int starCount = + ( i > number / ? number - i - : i ) * ;
int emptyCount = ( number - starCount ) /;
for (int j = ; j < emptyCount; j++)
{
Console.Write(" ");
}
for (int k = ; k < starCount; k++)
{
Console.Write("*");
}
Console.WriteLine("");
} Console.ReadKey();
}

2.冒泡排序

int[] scores = {,,,};

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