【问题标题】:C# Beginner, How to add Queue int to total int?C#初学者,如何将Queue int添加到total int?
【发布时间】:2023-04-03 01:55:01
【问题描述】:

这是要求:

请使用 while 循环遍历队列,然后添加下一个 项目到总变量。循环结束后,请将总数写入 使用 Console.WriteLine 的控制台。

这里是代码:

using System;
using System.Collections.Generic;

public class Program
{
    public static void Main()
    {
        Queue<int> primes = new Queue<int>();

        primes.Enqueue(2);
        primes.Enqueue(3);
        primes.Enqueue(5);
        primes.Enqueue(7);
        primes.Enqueue(11);

        int total = 0;

        while(primes.Count > 0)
        {
            total += primes.Dequeue();
        }
        Console.WriteLine(total);
    }
}

即使我得到 28 的输出,本教程也不会接受这个答案。我之前遇到过一个错误,所以我不确定我是正确的还是网站只是搞砸了。这是正确的吗?如果没有,我错过了什么?

https://dotnetcademy.net/Learn/2047/Pages/20

【问题讨论】:

  • 请停止使用该网站。它充满了错误。

标签: c# loops queue


【解决方案1】:

也许,他们希望您使用“foreach”而不是 while。使用下面的代码 sn-p 并提交给他们

    foreach (var Item in primes)
        total += Item;

【讨论】:

  • 方向字面意思是use a while loop
猜你喜欢
  • 1970-01-01
  • 2017-08-02
  • 1970-01-01
  • 2010-10-06
  • 2014-03-21
  • 1970-01-01
  • 2014-07-10
  • 2019-01-04
  • 1970-01-01
相关资源
最近更新 更多