c#为具有循环

时间:2015-09-01 05:15:01

标签: c# arrays

大家好,我最近开始了一项活动,我刚想到了这个活动。 我决定将用户输入分配给这样的数组

while (true) 
{                  
    int n = 0;
    int[] series = new int[n];

    Console.WriteLine("Please pick a number between 1 and 100:");
    series[n] = Convert.ToInt32(Console.ReadLine()); 
    // This block above creates errors saying it created an unhandled exception. 
    // I havent added a try and catch since this is just a trial a 
    // planned to add them once this program is working

    Console.WriteLine("Do you want to try again (Y/N): ");
    char tryagain = Convert.ToChar(Console.ReadLine());
    char.ToLower(tryagain);

    if (tryagain == 'y') 
    {
        for (int i = 0; i <= series.Length; i++) 
        {
            Console.WriteLine("Your numbers are {0}", series[n]);
        }
        break;
    }
    else 
    {
        n = n + 1;
    }
}

Console.ReadKey();

提前感谢您,我们非常感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

在你的代码中int [] series = new int [n];这也是创建一个0长度的数组。试试这个..

int n = 1;
int[] series = new int[n];

Console.WriteLine("Please pick a number between 1 and 100:");
series[n-1] = Convert.ToInt32(Console.ReadLine()); // set value for zero index

<强>已更新

数组长度不能增加运行时间。所以你可以使用list&lt;&gt;

static void Main(string[] args)
    {
        var series = new List<int>();
        while (true)
        {
            Console.WriteLine("Please pick a number between 1 and 100:");
            series.Add(int.Parse(Console.ReadLine()));
            Console.WriteLine("Do you want to try again (Y/N): ");
            if (Console.ReadLine().ToLower()[0] != 'y')
            {
                break;
            }
        }
        Console.WriteLine("Your numbers are:");
        foreach (var number in series)
        {
            Console.WriteLine(number);
        }
        Console.ReadLine();

    }

答案 1 :(得分:0)

尝试这样做:

<script>
function doit()
{
var sum=document.getElementById('new').value;
var extra=sum/10;
var newamount=sum + extra;
document.getElementById('new1').value=newamount;
}
</script>