C#学习第五天9.29

104 阅读1分钟

一、例题

1、3个可乐瓶换一瓶可乐,输入可乐数,输出可以喝几瓶还剩几个空瓶

    Console.WriteLine("请输入可乐瓶数");
    int n = Convert.ToInt32(Console.ReadLine());
    int ping = n;//喝完全部剩下的空瓶
    while (ping > 2)//大于2说明可以换可乐
    {
        n += ping / 3;//第一次喝完后,瓶子拿去换,又可以喝ping/3瓶
        //计算剩下的空瓶
        ping = ping / 3 + ping % 3;
    }
    Console.WriteLine("总共喝了{0},剩下{1}个空瓶",n,ping);

2、对输入的字符串进行加密,a-d,x-a,其他的不变

   char[] sList = Console.ReadLine().ToCharArray();// Console.ReadLine().ToCharArray();字符串转字符数组
   
    for (int i = 0; i < sList.Length; i++)//遍历数组中的内容
    {
        if (('a' <= sList[i] && sList[i] <= 'z') || ('A' <= sList[i] && sList[i] <= 'Z'))//数组中字母才要加密,其他字符不需要
        {
            if ('x' <= sList[i] || ('X' <= sList[i] && sList[i] <= 'Z'))//xyz是特殊情况,不需要小于z是因为小写字母比大写字母更大
            {
                sList[i] = Convert.ToChar(sList[i] + 23);
            }
            else
            {
                sList[i] = (char)(sList[i] + 3);
            }
        }
    }
    Console.WriteLine(string.Join("", sList));

2.2加密中的知识点

(1)将数组变为字符串 string.join(“连接符”,数组名)

例:

    string[] stList = { "1", "2", "3", "4" };//此时slist是一个数组
    Console.WriteLine(string.Join("-", stList))//将数组变为了字符串

(2)将字符串转为数组TocharArray

例:

 char[] slist = Console.ReadLine().ToCharArray();//将输入的字符串变为数组(假设输入ABCD,就是slist[A,B,C,D])

二、冒泡排序

1、随机输入一串数字,从小到大输出

 Console.WriteLine("请输入一串数字");
    char[] nums = Console.ReadLine().ToCharArray();
    //int[] nums = { 1, 12, 22, 2, 3, 5, 7, };
    for (int i = 1; i <= nums.Length - 1; i++)//总共要次循环的次数
    {
        for (int j = 0; j < nums.Length - i; j++)//两两比对的次数
        {
            //定义一个中间值temp
            char temp;
            if (nums[j] > nums[j + 1])
            {
                temp = nums[j];
                nums[j] = nums[j + 1];
                nums[j + 1] = temp;
            }
        }
    }
    Console.Write(String.Join(" ", nums));

1.1冒泡排序相关知识点:

(1)对数组进行排序//Array.Sort(数组名),对数组进行排序(会改变原来的数组)

int[] nums = { 2, 4, 5, 7, 8, 1 };
    Array.Sort(nums);
    Console.WriteLine(string.Join(" ",nums))//将数组变为字符串输出

2、有n(n<=100),已经按照从小到大排序好,现在另外给一个整数x,插入到序列中,并使新的序列仍然有序

 int[] nums = {1,23,12,14 };
     Array.Sort(nums);
     int x = Convert.ToInt32(Console.ReadLine());
     int a=0;//x插入的位置
     for (int i = 0; i < nums.Length - 1; i++)//nums的下标
     {
         if (x >= nums[i] && x <= nums[i + 1])
         {
             a = i+1;

         }
     }
         //特殊情况,x是最大的
         if (x >= nums[nums.Length-1])
         {
             a = nums.Length;

         }
         //重新生成新的数组
         int[] num2;
         num2 = new int[nums.Length + 1];
        for(int j = 0; j < a; j++)
         {
             num2[j] = nums[j];
         }
         num2[a] = x;
        for(int j = a+1; j < num2.Length; j++)
         {
             num2[j] = nums[j - 1];
         }
        Console.WriteLine(string.Join(" ", num2));