【问题标题】:C# adding dynamic variables in loopC#在循环中添加动态变量
【发布时间】:2014-04-13 23:25:10
【问题描述】:

这是一个相当菜鸟的问题。 这是我的代码

double jury;
jury = double.Parse(Console.ReadLine());
for (int i = 0; i < jury ; i++)
{
    Console.ReadLine();
}

如何在循环内定义输入,以便可以使用来自附加输入的输入数据进行数学计算。 这是一个投票系统,第一个变量是陪审团人数——每个陪审团成员投票给一个数字 1-10。这个想法是陪审团是动态的,从 1 到 100,000。欢迎任何想法。

更多:这就是想法。

-> 例如,当您有 3 名陪审团成员时

-> 你在第一行输入 3

-> 您将获得 3 个新的输入,您的陪审团投票给候选人(编号 1 到 10)

-> 在这种情况下,投票是 1, 3, 3

这个想法是解析所有这些信息并输出获胜者,在我们的例子中是“3”。

【问题讨论】:

标签: c# variables dynamic


【解决方案1】:

您可以使用List&lt;T&gt;来存储投票;恕我直言,int 在您的任务中看起来比 Double 更好

Console.WriteLine("Enter number of jurors, please"); 

int jury;

if (!int.TryParse(Console.ReadLine(), out jury)) { 
  Console.WriteLine("Incorrect jury number format");

  return; // <- I'd exit on the first error occured; you may adopt different policy
}
else if ((jury < 1) || (jury > 100000)) {
  Console.WriteLine("Jury should be in range [1..100000]");

  return;
}

var List<int> = new List<int>();

for (int i = 0; i < jury; ++i) {
  int vote;

  Console.WriteLine("Enter next vote, please"); 

  if (!int.TryParse(Console.ReadLine(), out vote)) {
    Console.WriteLine("Incorrect vote format");

    return;
  }
  else if ((vote < 1) || (vote > 10)) {
    Console.WriteLine("Each vote should be in range [1..10]");

    return;
  }

  votes.Add(vote);
} 

【讨论】:

    【解决方案2】:

    此代码会提示一些陪审员并验证输入。然后,它会提示每个陪审员的投票,验证投票输入。

    const int minimumVote = 1;
    const int maximumVote = 10;
    int jurorCount;
    
    do
    {
        Console.Write("Enter the number of jurors: ");
    } while (!Int32.TryParse(Console.ReadLine(), out jurorCount) || jurorCount < 0);
    
    var votes = new List<int>();
    
    for (int i = 0; i < jurorCount; i++)
    {
        int vote;
    
        do
        {
            Console.Write("Enter juror #{0}'s vote ({1}-{2}): ", i + 1, minimumVote, maximumVote);
        } while (!Int32.TryParse(Console.ReadLine(), out vote) || vote < minimumVote || vote > maximumVote);
    
        votes.Add(vote);
    }
    

    【讨论】:

    • 我使用 do/while 而不是 while 重写了代码。这消除了一些额外的行。我还引入了两个常量来避免违反 DRY。
    【解决方案3】:

    使用列表或数组

    var values = new List<double>();
    for (int i = 0; i < jury; i++)
    {
        double current;
        if (double.TryParse(Console.ReadLine(), out current))
        {
           values.Add(current);
        }
        else
          i--;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-07-14
      • 2021-12-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多