代碼(1)
int[] nums = new int[10]; int[] count = new int[4];
try
{
for (int i = 0; i < nums.Length; i++)
{
Console.Write("請輸入第{0}個數字",i+1);
nums[i] = Convert.ToInt32(Console .ReadLine());
if (nums [i]==1)
{
count[0]++;
}
else if (nums [i]==2)
{
count[1]++;
}
else if (nums [i]==3)
{
count[2]++;
}
else
{
count[3]++;
}
}
Console.WriteLine("數字1的個數為:{0}",count[0]);
Console.WriteLine("數字2的個數為:{0}", count[1]);
Console.WriteLine("數字3的個數為:{0}", count[2]);
Console.WriteLine("非法數字的個數為:{0}", count[3]);
}
catch
{
Console.WriteLine("輸入有誤概龄,請重新輸入聘萨!");
}
Console.ReadKey();
代碼(2)
int[] nums = new int[10]; int[] count = new int[4];
try
{
for (int i = 0; i < nums.Length; i++)
{
Console.Write("請輸入第{0}個數字:",i+1);
nums [i] = Convert.ToInt32(Console.ReadLine());
switch (nums[i])
{
case 1:
count[0] += 1;
break;
case 2:
count[1] += 1;
break;
case 3:
count[2] += 1;
break;
default:
count[3] += 1;
break;
}
}
Console.WriteLine("數字1的個數為:{0}", count[0]);
Console.WriteLine("數字2的個數為:{0}", count[1]);
Console.WriteLine("數字3的個數為:{0}", count[2]);
Console.WriteLine("非法數字的個數為:{0}", count[3]);
}
catch
{
Console.WriteLine("輸入有誤,請重新輸入!");
}
Console.ReadKey();
效果
image.png