添加每个双位数字的数字

时间:2015-06-25 17:38:42

标签: c# loops sum digits

这是我的代码。我想让用户连续输入任意数量的双打,直到100次(可能是用户想要的次数但少于100次)。显示输入的所有值的总和。在我的代码中,我不知道如何允许用户连续输入数字(我猜你会有一个while循环)。 非常感谢!

Console.WriteLine("Enter double");
    double.first = double.Parse(Console.ReadLine());

    while(first != 0)
    {
        Console.WriteLine("Enter double");
        int num = int.Parse(Console.ReadLine());
        double sum;
        while(num != 0)
            {
            double ten = num/10; 
            double tenth = Math.Floor(ten);
            double oneth = num % 10;
            sum = tenth + oneth; 
            Console.WriteLine("{0}", sum);
            break;

            }

        first = double.Parse(Console.ReadLine());

    }

2 个答案:

答案 0 :(得分:1)

评论后编辑:

好的,我仍然认为这是家庭作业,但这里有基础......

我会分两个阶段,数据输入,然后计算。

创建用于存储输入的内容和用于循环的计数器

var inputs = new List<double>();
var counter = 0;

现在来到你的输入循环...

while(counter < 100)
{
    var tempInput = 0.0D;
    Double.TryParse(Console.ReadLine(), out tempInput);
    if(tempInput == 0.0D)
    {
        // The user did not enter something that can be parsed into a double
        // If you'd like to use that as the signal that the user is finished entering data,
        // just do a break here to exit the loop early
        break;
    }
    inputs.Add(tempInput);
    // This is your limiter, once counter reaches 100 the loop will exit on its own
    counter++;
}

现在,您只需对已累积的值进行计算......

var total = 0.0D;
foreach(var value in inputs)
{
    total += value;
}

现在显示总值。

请记住,有很多方法可以做到这一点,这只是让您解决获取数据问题的一个例子。

答案 1 :(得分:1)

I want to have users enter any number of doubles continuously until 100 times (could be however number of times the user wants but less than 100). You need to keep track of 3 things. The next double. The running total. How many times the user has provided input. Variables: double next; double runningTotal = 0; int iterations = 0; Now, to continuously receive input from the user, you can write a while-loop as you correctly identified. In this loop you should check for two things: That the next value is a double and that it is not 0. That the user has not provided input more than 100 times. While-loop: while (double.TryParse(Console.ReadLine(), out next) && next != 0 && iterations < 100) { // Count number of inputs. iterations++; // Add to the running total. runningTotal += next; } Display sum of all values entered. Simply write to the console. Output: Console.WriteLine("You entered {0} number(s) giving a total value of {1}", iterations+1, runningTotal); Complete example: static void Main() { double runningTotal = 0; double next; var iterations = 0; Console.Write("Enter double: "); while (double.TryParse(Console.ReadLine(), out next) && next != 0 && iterations < 100) { runningTotal += next; iterations++; Console.Write("Enter double: "); } Console.WriteLine("You entered {0} number(s) giving a total value of {1}", iterations+1, runningTotal); Console.Read(); }