你怎么重复输入的总数?

时间:2014-11-29 22:52:12

标签: c#

我对c#很新,我不能很快得到它。如果你能解释如何以及为什么喜欢和3岁的老人交谈那就太棒了!!!

你怎么做(输入金额(-1来停止))重复并最终得到所有输入的金额?

2 个答案:

答案 0 :(得分:1)

我们称它为循环,小男孩:P
更新我不知道我是否理解你,但现在代码每次写入总和,如果你输入例如-5,它将是sum = sum - 5

class Program
{
    static void Main(string[] args)
    {
        // thoose are variables, and they are storing data
        int input = 0; // input integer number
        int sum = 0; // sum of all numbers

        while (true) //Infinite loop (executes undereneath code until true=true)
        {
            input = int.Parse(Console.ReadLine()); // read the line from user, parse to int, save to input variable
            if (input == -1) break; // if integer input is -1, it stops looping (the loop breaks) and GOES  (two lines down)
            sum = sum+ input; // summing all input (short version -> s+=input)
            Console.WriteLine("Actual Sum: "+sum);  // HERE IS THE UPDATE
        }
          //HERE
        Console.WriteLine("Your final sum is: " + s);
    }
}

答案 1 :(得分:1)

幸运的是,我3岁的孩子就坐在这里,所以我让他写出来了:)

var total = 0;  // This will hold the sum of all entries
var result = 0;  // This will hold the current entry

// This condition will loop until the user enters -1
while (result != -1)
{
    // Write the prompt out to the console window
    Console.Write("Enter the amount (-1 to stop): ");

    // Capture the user input (which is a string)
    var input = Console.ReadLine();

    // Try to parse the input into an integer (if TryParse succeeds, 
    // then 'result' will contain the integer they entered)
    if (int.TryParse(input, out result))
    {
        // If the user didn't enter -1, add the result to the total
        if (result != -1) total += result;
    }
    else
    {
        // If we get in here, then TryParse failed, so let the user know.
        Console.WriteLine("{0} is not a valid amount.", input);
    }
}

// If we get here, it means the user entered -1 and we exited the while loop
Console.WriteLine("The total of your entries is: {0}", total);