C#基础练习
1、冒泡排序
namespace _0 { class Program { public static int[] BubbleSort(int[] arr) { for (int i = 0; i < arr.Length - 1; i++) { for (int j = 0; j < arr.Length - 1; j++) { if (arr[j] > arr[j + 1]) { int temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; } } } return arr; } static void Main(string[] args) { int[] numbers = { 2, 5, -7, 9, 3, 2, 1, -3, 0, 2 }; int[] result = BubbleSort(numbers); for (int i = 0; i < result.Length; i++) { Console.Write("{0} ", result[i]); } Console.ReadKey(); } } }
2、100~999之间的水仙花数
namespace _0 { class Program { public static bool Daffodils(int arr) { int hundreds = arr / 100; // 获取百位数 int ten = arr / 10 % 10; // 获取十位数 int single = arr % 10; // 获取个位数 int n = (hundreds * hundreds * hundreds) + (ten * ten * ten) + (single * single * single); if (arr == n) { return true; } return false; } static void Main(string[] args) { for (int i = 100; i < 999; i++) { bool flag = Daffodils(i); if (flag) { Console.WriteLine("Daffodils: {0}", i); } } Console.ReadKey(); } } }
3、取出数组中最大值和最小值
namespace _0
{
class Program
{
public static int[] ReturnMaxAndMin(int[] arr)
{
int[] result = { arr[0], arr[0] };
for (int i = 0; i < arr.Length; i++)
{
if (arr[i] > result[0])
{
result[0] = arr[i];
}
else if (arr[i] < result[1])
{
result[1] = arr[i];
}
}
return result;
}
static void Main(string[] args)
{
int[] arrary = { 1, 2, 4, 6, 7, 8, -1, 2, -4 };
int[] numbers = ReturnMaxAndMin(arrary);
Console.WriteLine("Max number: {0}, Min number: {1}", numbers[0], numbers[1]);
Console.ReadKey();
}
}
}