我应该使用哪个循环来在C#程序下面获得正确的结果

时间:2016-12-09 21:15:10

标签: c# loops average

在我的程序中,我知道发生了什么,但不知道我应该使用哪个循环。这是代码。非常感谢您的帮助。

如果您需要更多信息来了解我的问题,请与我们联系。

using System;

// Write a C# program that takes x numbers as input to calculate and print the average. 
class Program9
{
    int input, i = 1, val, sum;

    decimal avg;

    public void program9M()
    {
        Console.Write("How many number(s) you have for an average: ");
        input = Convert.ToInt32(Console.ReadLine());

        if (input >= 2)
        {
            do
            {
                Console.Write("Enter number {0} for an average: ", i);
                val = Convert.ToInt32(Console.ReadLine());
                sum = sum + val;
                i += 1;
            } while (i <= input);

            avg = (decimal)sum / i;
            Console.WriteLine("The average of above {0} number is: {1}", i, avg);
        }
        else
        {
            Console.WriteLine("\n\nSorry you can't find average for one number, at least 2 number required\n\n");
        }

        Console.Write("Press any key to continue further...");
        Console.ReadKey();
    }

    public static void Main()
    {
        Program9 p9 = new Program9();
        p9.program9M();
    }
}

输入:

How many number(s) you have for an average: 3

Enter number 1 for an average: 5

Enter number 2 for an average: 10

Enter number 3 for an average: 15

当前输出:

The average of above **4** number is: **7.5**

预期产出:

The average of above **3** number is: **10**

3 个答案:

答案 0 :(得分:1)

您可以大幅清理该代码。

int index = 0, input, averageInput;
var collection = new List<int>();
if(int.TryParse(Console.ReadLine(), out input) && input >= 2)
{
     while(index <= input)
     {
          if(int.TryParse(Console.ReadLine(), out averageInput)
             collection.Add(averageInput);

          index++;
     }

     var sum = collection.Sum();
     var average = collection.Average();
}

您需要处理错误。但是,您可以使用Linq而不是自己进行计算。这将使它更具表现力。此外,如果你自己做,你不需要:sum = sum + average你可以做:sum += average并且它会不断添加。

您还可以使用++--自动递增和递减。因此,您不需要i += 1,只需执行i++

你也应该从零开始一个循环,因为一个集合将从零基础而不是一个开始。因此,如果您的阵列有五个,并且从一个开始,您将只获得四个值。由于数组初始化为零。

答案 1 :(得分:0)

问题是do循环的工作原理。

更改int input, i = 0, val, sum;并将您的i增量移至顶部。此外,由于我们从0开始,因此将i的比较小于输入。

class Program9

{

    int input, i = 0, val, sum;

    decimal avg;

    public void program9M()

    {

        Console.Write("How many number(s) you have for an average: ");
        input = Convert.ToInt32(Console.ReadLine());
        if (input >= 2)
        {
            do
            {
                i += 1;
                Console.Write("Enter number {0} for an average: ", i);
                val = Convert.ToInt32(Console.ReadLine());
                sum = sum + val;

            } while (i < input);
            avg = (decimal)sum / i;
            Console.WriteLine("The average of above {0} number is: {1}", i, avg);
        }

        else
        {
            Console.WriteLine("\n\nSorry you can't find average for one number, at least 2 number required\n\n");

        }
        Console.Write("Press any key to continue further...");
        Console.ReadKey();
    }

    public static void Main()

    {
        Program9 p9 = new Program9();
        p9.program9M();
    }

}

}

答案 2 :(得分:0)

在那里使用的最佳循环是'for'循环,但有了它,它也可以工作。 你这样做的错误是'i'在开始时应为0,而在'(i&lt; input)'时应为0。所以带有该循环的代码看起来是:

for (int i = 0; i < input; i++)
{
    Console.Write("Enter number {0} for an average: ", i);
    val = Convert.ToInt32(Console.ReadLine());
    sum = sum + val;
}

avg = (decimal)sum / input;
Console.WriteLine("The average of above {0} number is: {1}", input, avg);

对于'for'循环,在这种情况下更常见的用法是:

function findTweets(params, num)
{
     params = {
        q: params, 
        count: num ,
        language: 'en' 
     }
     T.get('search/tweets', params, function(err, data, response) {
         console.log("first call");
        });

     console.log("second call");
}
findTweets("a str",1)
console.log("third call");

也没有必要除以'i',因为'输入'总是数字的数量。