【问题标题】:When input is 0 stop taking values当输入为 0 时停止取值
【发布时间】:2013-05-24 17:04:18
【问题描述】:

我需要代码,它从用户那里获取输入,然后将它们加在一起——很简单。但是我找不到一种方法,在按下 0 之前进行输入,然后将数字加在一起.. 到目前为止,我已将其设为 10 个值,但就像我说的那样,它需要自定义。感谢您的帮助。

int[] myarray = new int[10];
for (int i = 0; i < 10; i++)
{
    myarray[i] = Convert.ToInt32(Console.ReadLine());
}

int a = 0;
for (int j = 0; j < 10; j++)
{
    a = a + myarray[j];
}

Console.WriteLine(a);
Console.ReadLine();

【问题讨论】:

  • 你有什么尝试吗?进展如何?是否有特定原因需要记录所有值,还是只需要总和?
  • 我是新手,这是我的编程课的一部分,所以我仍然知之甚少。我尝试搜索类似的东西,但我没有找到它。如果我会一个例子我会知道怎么做。但遗憾的是我没有:(是的,我只需要总和。
  • 您不需要“代码”,您需要“代码”。 :)

标签: c# arrays for-loop int


【解决方案1】:

下面的代码不限于10个输入,你可以给任意多的输入

int sum=0, input;
do
{
    input = Convert.ToInt32(Console.ReadLine());
    sum += input;
}
while(input != 0);

Console.WriteLine(sum);
Console.ReadLine();

【讨论】:

    【解决方案2】:

    添加前检查输入,如果为0则break退出循环:

    int input = Convert.ToInt32(Console.ReadLine());
    if(input == 0) 
    {
      break;
    }
    
    myarray[i] = input;
    

    【讨论】:

    • 注意: 在第二个循环中硬编码的10 应更改为myarray.Length 以避免IndexOutOfRangeException。或者更好的是,应该使用foreach 循环。
    • @PLB - 看到两个循环的长度相同,这是一个真正的问题吗?
    【解决方案3】:

    由于您不知道数组的长度,我建议使用列表。我还添加了一个 tryparse 来应对狡猾的用户输入。您可以在列表中使用 Sum() 来避免写出另一个循环。

            IList<int> myList = new List<int>();
            string userInput = "";
            int myInt = 0;
    
            while (userInput != "0")
            {
                userInput = Console.ReadLine();
                if(Int32.TryParse(userInput, out myInt) && myInt > 0)
                {
                    myList.Add(myInt);
                }
            }
    
            Console.WriteLine(myList.Sum());
            Console.ReadLine();
    

    【讨论】:

    • Sarwar 的解决方案更优雅,我关注的是数组而不是最终目标。 :)
    【解决方案4】:

    当你有一个未知大小的数组时,你应该使用一个列表。

    var ls = new List<int>();
    
        while(true)
        {
            var input = Convert.ToInt32(Console.ReadLine());
            if(input == 0) 
                break;
    
            ls.Add(input);
        }
    

    Lists by MSDN

    【讨论】:

      【解决方案5】:

      你可以使用这样的东西:

      while(true)
      {
          int input = Convert.ToInt32(Console.ReadLine());
          if(input == 0)
              break;
      
          //do you math here
      }
      

      【讨论】:

        猜你喜欢
        • 2022-11-25
        • 2016-01-28
        • 1970-01-01
        • 1970-01-01
        • 2020-11-04
        • 1970-01-01
        • 2022-08-20
        • 2019-05-11
        • 1970-01-01
        相关资源
        最近更新 更多