利用一维数组求解问题。读入若干(1-15个)整数(一行输入,空格分隔),每个数在10-100之间的整数包括10和100。在读入每个数时,确认这个数的有效性(在10到100之间),并且若它和之前读入的数不一样,就把它存储到数组中,无效的数不存储。读完所有数之后,仅显示用户输入的不同的数值。
样例1:
输入:
12 34 99 123 12 123 78 0 12 99
输出:
12 34 99 78
样例2:
输入:
-9 -9 0 34 99 99 99 34 34 34
输出
34 99
题目分析:
1.读入输入字符串,用空格进行分割字符串,变成字符串数组
2.用for循环遍历字符串数组,将其转化成int整型,判断数是否有效,判断数组中是否存在此数,不存在就加入到数组中
3.用foreach语句按题目要求格式输出数组中的数字
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication5 { class Program { static void Main(string[] args) { string str = Console.ReadLine(); string[] strarr = str.Split(' '); List<int> iList = new List<int>(); for (int i = 0; i < strarr.Length; i++) { int num = Convert.ToInt32(strarr[i]); if (num > 100 || num < 10) continue; bool CheckNum = false; for (int j = 0; j < iList.ToArray().Length; j++) { if (num == iList[j]) { CheckNum = true; break; } } if (!CheckNum) iList.Add(num); } foreach(int i in iList) { Console.Write("{0} ", i); } Console.Read(); } } } |