首页 > 代码库 > Net基础篇_学习笔记_第九天_数组_三个练习

Net基础篇_学习笔记_第九天_数组_三个练习

练习一:

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 
 7 namespace _数组练习01
 8 {
 9     class Program
10     {
11         static void Main(string[] args)
12         {
13             string str = null;
14             string[] names = { "老杨","老李","老赵","老孙","老沈"};
15             for (int i = 0; i < names.Length; i++)
16             {
17                 str += names[i] + "|";
18             }
19             Console.WriteLine(str);
20             Console.ReadKey();
21         }
22     }
23 }

优化为:

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 
 7 namespace _数组练习01
 8 {
 9     class Program
10     {
11         static void Main(string[] args)
12         {
13             string str = null;
14             string[] names = { "老杨","老李","老赵","老孙","老沈"};
15             for (int i = 0; i < names.Length-1; i++)
16             {
17                 str += names[i] + "|";
18             }
19             Console.WriteLine(str+names[names.Length-1]);
20             Console.ReadKey();
21         }
22     }
23 }

 练习二:如遇正数,将这个位置元素的值加1,如遇负数,将这个位置元素的值减1,如遇0,则不变。

int nums={0,5,-8,-41,5,94,-1,-22};

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 
 7 namespace _数组练习01
 8 {
 9     class Program
10     {
11         static void Main(string[] args)
12         {
13             int[] nums = { 66,58,841,-556,-121,-541,55};
14             for (int i = 0; i < nums.Length; i++)
15             {
16                 if (nums[i] > 0)
17                 {
18                     nums[i] += 1;
19                 }
20                 else if (nums[i] < 0)
21                 {
22                     nums[i] -= 1;
23                 }
24             }
25             for (int i = 0; i < nums.Length; i++)
26             {
27                 Console.WriteLine(nums[i]);
28             } 
29             Console.ReadKey();
30         }
31     }
32 }

 

Net基础篇_学习笔记_第九天_数组_三个练习