计算c#中序列号的平均值

时间:2014-11-21 03:28:52

标签: c#

我想创建序列号,当用户输入“0”时,它应该停止并将数字保存在内存中,然后询问用户是否显示这些数字的总数或显示平均值。总看起来不错,但是当我选择平均值时,我的控制台没有响应,它崩溃了。

using System;

class ETA11
{
    public static int Main()
    {
        ETA11_3();
        return 0;
    }
    public static void ETA11_3()
    {
        int number = 0, total = 0, option = 0, counter = 0, average = 0;
        do
        {
            Console.WriteLine("Input a number (zero for stop): ");
            number = Int16.Parse(Console.ReadLine());
            total += number;

            if (number == 0) break;
        } while (option != 2);
        Console.WriteLine("Choose an option: ");
        Console.WriteLine("1 - Total");
        Console.WriteLine("2 - Average");
        counter++;
        option = Int16.Parse(Console.ReadLine());
        switch (option)

        {
            case 1:
                Console.WriteLine("Total: {0}", total);
                break;
            case 2:
                Console.WriteLine("Total: {0}", total / number);
                break;
            default:
                Console.WriteLine("Invalid Option");
                break;
        }
    }
}

2 个答案:

答案 0 :(得分:2)

当您选择选项2时,您正在划分0

Console.WriteLine("Total: {0}", total / number);

我相信你想要除以counter

Console.WriteLine("Total: {0}", total / (decimal) counter);

但是,你需要将counter++放在你的whileloop中

答案 1 :(得分:0)

正如Neverever所提到的,你用数字除以0导致DividedByZeroException。我还将正确的计数器合并到你的循环中并清理了你的do {} while()循环(使用不当)。

以下是更正的方法:

public static void ETA11_3()
{
    int number = 0, total = 0, option = 0;
    double counter = 0d;
    while (true)
    {
        Console.WriteLine("Input a number (zero for stop): ");
        number = Int16.Parse(Console.ReadLine());
        total += number;

        if (number == 0) break;
        counter++;
    }
    Console.WriteLine("Choose an option: ");
    Console.WriteLine("1 - Total");
    Console.WriteLine("2 - Average");
    option = Int16.Parse(Console.ReadLine());
    switch (option)
    {
        case 1:
            Console.WriteLine("Total: {0}", total);
            break;
        case 2:
            Console.WriteLine("Total: {0}", total / counter);
            break;
        default:
            Console.WriteLine("Invalid Option");
            break;
    }
}