嗯,我試圖做一個簡單的程序,利用for循環並將用戶輸入添加到一次一個數組,這使用此如何循環通過用戶輸入c#創建的數組#
string []str = new string[10];
for (int i = 0; i < str.Length; i++)
{
Console.WriteLine("Please enter a number: ");
str[i] = Console.ReadLine();
}
但是,當我嘗試通過數組與foreach語句循環,我得到一個錯誤,指出我不能隱式轉換字符串[]以鍵入字符串; foreach語句是這樣的:
int even=0; int odd=0;
int[] Arr=new string [] {str};
foreach (int i in Arr)
{
if (i % 2 == 0)
{
even++;
}
else
{
odd++;
}
}
這裏是完整的源代碼,
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string[] str = new string[10];
for (int i = 0; i < str.Length; i++)
{
Console.WriteLine("Please enter a number: ");
str[i] = Console.ReadLine();
}
int even = 0; int odd = 0;
int[] Arr = new string[] { str };
foreach (int i in Arr)
{
if (i % 2 == 0)
{
even++;
}
else
{
odd++;
}
}
Console.WriteLine("There is " + even + " even numbers.");
Console.WriteLine("There is " + odd + " odd numbers");
Console.ReadLine();
Console.ReadLine();
}
}
}
因爲你創建一個整數數組,並嘗試填充/使用字符串初始化。在第二個代碼框中檢查第二行代碼 –