负数C#的总和

 收藏

C#循环。 我需要这个问题的帮助:

编写一个程序,该程序从键盘读取10个数据并仅添加负数。

我刚在一月份开始上课,当时我们处于C#循环中。由于冠状病毒,我已经上学三个多星期了。所以我现在有点迷失了,我们才开始在线课程,对我来说是那么大的撕裂:(

        double sum = 0.0d;
        double n = 0.0d;

        for (int i = 1; i <= 10; i++)
        {
            Console.Write($"Enter a number {i}: ");
            n = double.Parse(Console.ReadLine());
        }

        if (n < 0)
            sum = n + n;

        Console.WriteLine($"{sum}");

这是我的代码(我可能是100%错误,但现在是凌晨2点,我正在尝试);

谢谢! :)

回复
  • Actually, you're closer than you think. You should adjust the sum inside the loop, and it should be adjusted by adding n to the current sum rather than setting it to n + n.

    By adjusting after the loop is finished, you only take the last number in to account. And, by setting sum to n + n, the sum you end up with will just be twice the last number entered if it was negative, and zero if not.

    换句话说,类似:

    double sum = 0.0d;
    double n = 0.0d;
    
    for (int i = 1; i <= 10; i++)
    {
        Console.Write($"Enter a number {i}: ");
        n = double.Parse(Console.ReadLine());
        if (n < 0)
            sum = sum + n;
    }
    
    Console.WriteLine($"{sum}");
    

  • 您正在添加循环之外的总和...

    如果在分配n之后将其移动到循环中,则将n加到sum而不是n上,那么你就很好