简体   繁体   English

如何使用 c# 中的 for 循环中的数字进行加法?

[英]How can i make a addition with the numbers from for loop in c#?

I am a newbie on c# and I am trying to make a calculator.我是 c# 的新手,我正在尝试制作一个计算器。 In these codes, I am trying to take the values from input in a for loop and make an addition with them.在这些代码中,我试图从 for 循环中的输入中获取值并对其进行添加。 But I couldn't do it.但我做不到。 How can I do this?我怎样才能做到这一点?

using System;
using System.Text;

namespace cihantoker
{
    class Program1
    {
        public static void Main()
        {
            Console.WriteLine("Please enter your operation:");
            Console.WriteLine("[1]Addition");
            Console.WriteLine("[2]Subtraction");
            Console.WriteLine("[1]Multiplacition");
            Console.WriteLine("[1]Division");
            String operation = Console.ReadLine();
            //Addition Begins
            if (operation == "1")
            {

                Console.WriteLine("Please enter the count of the numbers that you want to make addition:");
                String NumberCount = Console.ReadLine();
                int Numbercount = int.Parse(NumberCount);
                for (int i = 0; i < Numbercount; i++)
                {
                    String NumberToMakeAddition = Console.ReadLine();
                    int NumberToMakeAddition2 = int.Parse(NumberToMakeAddition);

                }
            }
        }
    }
}

You aren't adding any numbers in your for loop.您没有在 for 循环中添加任何数字。 You are overwriting the value of NumberToMakeAddition2 with each number you parse.您正在用解析的每个数字覆盖 NumberToMakeAddition2 的值。

Define NumberToMakeAddition2 outside the for loop and initialize it to 0. Add each number that you parse to the sum.在 for 循环之外定义 NumberToMakeAddition2 并将其初始化为 0。将您解析的每个数字添加到总和中。

You have no error handling so be careful if the text entered is not an integer.您没有错误处理,因此如果输入的文本不是 integer,请小心。

I will suggest you use int.TryParse() instead of int.Parse since we cannot trust the input from the console.我建议您使用int.TryParse()而不是int.Parse ,因为我们不能信任来自控制台的输入。 And the only thing you need to do here is to declare one variable outside the loop and keep the sum in that variable while looping.您在这里唯一需要做的就是在循环外声明一个变量,并在循环时将总和保存在该变量中。 A sample code will be like the following:示例代码如下所示:

if (operation == "1")
{
    Console.WriteLine("Please enter the count of the numbers that you want to make addition:");
    int.TryParse(Console.ReadLine(), out int numberCount);
    int sumOfNumbers = 0;
    for (int i = 0; i < numberCount; i++)
    {
        if (int.TryParse(Console.ReadLine(), out int numberInput))
        {
            sumOfNumbers += numberInput;
        }
        else
        {
            Console.WriteLine("Wrong input from console, skipping the number");
        }
    }
    Console.WriteLine($"Sum of numbers :{sumOfNumbers}");
}

Cihan, First, you are assuming people would make inputs that are parseable to int. Cihan,首先,您假设人们会进行可解析为 int 的输入。 That may not be the case.情况可能并非如此。 Check and study int.TryParse() for that matter.检查并研究 int.TryParse() 。 Second, in your loop, you are redeclaring a NEW variable NumberToMakeAdition2 and assigning the parsed value to it.其次,在您的循环中,您正在重新声明一个新变量 NumberToMakeAdition2 并将解析后的值分配给它。 There is no addition there.那里没有添加。 What you should do is to initialize it before the loop, say:您应该做的是在循环之前对其进行初始化,例如:

int sum = 0;

and then in loop add to it:然后在循环中添加:

sum += int.Parse(...) // remember TryParse, just keeping it simple here

Create a List like this: List<int> myList = new List<int>() , to push all your users numbers into.像这样创建一个列表: List<int> myList = new List<int>() ,将所有用户号码推入。 In your loop, when you parse the users entry, use myList.Add(NumberToMakeAddition) .在您的循环中,当您解析用户条目时,请使用myList.Add(NumberToMakeAddition) Then, after your loop, you can do MyList.Sum() , or you can loop through your list and add them one at a time然后,在您的循环之后,您可以执行MyList.Sum() ,或者您可以遍历您的列表并一次添加一个

I have made some correction in the code.我在代码中做了一些更正。 you are using = operator which every time assign/store number(which need to add) to variable NumberToMakeAddition2.您正在使用 = 运算符,每次将编号(需要添加)分配/存储到变量 NumberToMakeAddition2。 So output is last entered number.所以 output 是最后输入的数字。

For Desired output or Proper implementation of addition, Need to do three things:-对于所需的 output 或正确执行加法,需要做三件事:-

  1. Declare NumberToMakeAddition2 outside the for loop and set zero.在 for 循环外声明 NumberToMakeAddition2并设置为零。
  2. Use += operator which add each entered/input number in NumberToMakeAddition2 if it is valid int.使用 += 运算符,如果它是有效的 int,则在 NumberToMakeAddition2 中添加每个输入/输入的数字。 in background it is like this:-在后台是这样的:-

NumberToMakeAddition2 += entered number; NumberToMakeAddition2 += 输入的数字;

is same as the below与以下相同

NumberToMakeAddition2 = NumberToMakeAddition2 + entered number; NumberToMakeAddition2 = NumberToMakeAddition2 + 输入的数字;

  1. Exception Handling :- input can be entered as string also or invalid number like special character or any string so system/code will throw exception and crash but in this requirement system/code should give proper message and ignore invalid.异常处理:- 输入也可以作为字符串输入,也可以输入无效数字,如特殊字符或任何字符串,因此系统/代码将引发异常和崩溃,但在此要求中,系统/代码应给出正确的消息并忽略无效。 For this, use either int.TryParse() or Convert.ToInt32().为此,请使用 int.TryParse() 或 Convert.ToInt32()。

     1. int.TryParse():- Do not need to use try catch but it does not handle null value and in this case(console) input cannot be null so **int.TryParse() is more appropriate**. 2. Convert.ToInt32():- Can handle null but need try catch to give proper message in catch and code looks clumsy.

using System;使用系统; using System.Text;使用 System.Text;

namespace cihantoker
{
    class Program1
    {
        public static void Main()
        {
            Console.WriteLine("Please enter your operation:");
            Console.WriteLine("[1]Addition");
            Console.WriteLine("[2]Subtraction");
            Console.WriteLine("[1]Multiplacition");
            Console.WriteLine("[1]Division");
            String operation = Console.ReadLine();
            //Addition Begins
            if (operation == "1")
            {

                Console.WriteLine("Please enter the count of the numbers that you want to make addition:");
                                    
                if (int.TryParse(Console.ReadLine(), out int Numbercount))
                {
                   int NumberToMakeAddition2 = 0;
                   for (int i = 0; i < Numbercount; i++)
                   {
                     if (int.TryParse(Console.ReadLine(), out int number))
                     {
                        NumberToMakeAddition2 += number;
                     }
                     else
                     {
                        Console.WriteLine("You entered invalid number, Ignoring this and please enter valid number");
                     }
                   }
                }
                else
               {
                 Console.WriteLine("Please enter valid number");
               }
                
            }
        }
    }
}

This being C# and highly object-oriented you are doing yourself a disservice by treating it as script and having all your code under Main() .这是C#并且高度面向对象,您将其视为脚本并将所有代码都放在Main()下,这是对自己的伤害。

In C# think about a data model.C#考虑数据 model。 How do I define objects that hold the information I wan't.如何定义包含我不需要的信息的对象。 In this example I want to make a calculator, and so I design a class that holds the calculator result, and can perform the basic operations to this result.在这个例子中我想做一个计算器,所以我设计了一个 class 来保存计算器的结果,并且可以对这个结果进行基本的操作。

Data Model数据 Model

public class Calculator
{
    public Calculator()
    {
        Result = 0;
    }
    /// <summary>
    /// Hold the result of the calculations
    /// </summary>
    public int Result { get; set; }
    /// <summary>
    /// Adds a number to the result
    /// </summary>
    /// <param name="x">The number.</param>
    public void Add(int x)
    {
        Result += x;
    }
    /// <summary>
    /// Subtracts a number from the result
    /// </summary>
    /// <param name="x">The number.</param>
    public void Subtract(int x)
    {
        Result -= x;
    }
    /// <summary>
    /// Multiplies the result with a number
    /// </summary>
    /// <param name="x">The number.</param>
    public void Multiply(int x)
    {
        Result *= x;
    }
    /// <summary>
    /// Divides the result with a number
    /// </summary>
    /// <param name="x">The number.</param>
    public void Divide(int x)
    {
        Result /= x;
    }
}

The above is pretty straightforward.上面的很简单。 There are four methods that modify the result, and one constructor to initialize the data.有四种方法可以修改结果,以及一种构造函数来初始化数据。

Program程序

The actual program should then define and act on the data model.然后,实际程序应定义数据 model 并对其进行操作。 I chose to have an infinite loop when the user can select the next action, and can exit the loop by just pressing enter当用户可以 select 下一个动作时,我选择了无限循环,并且只需按 enter 即可退出循环

class Program
{
    static void Main(string[] args)
    {
        // calculator object iniialized
        Calculator calculator = new Calculator();
        // Inifinte loop
        while (true)
        {
            // Report the caclulator result
            Console.WriteLine($"Result = {calculator.Result}");
            Console.WriteLine();
            Console.WriteLine("Select Operation:");
            Console.WriteLine(" [1] Addition");
            Console.WriteLine(" [2] Subtraction");
            Console.WriteLine(" [3] Multiplication");
            Console.WriteLine(" [4] Division");
            Console.WriteLine(" [ENTER] Exit");
            string input = Console.ReadLine();
            // Check if user entered a number
            if (int.TryParse(input, out int operation))
            {
                Console.WriteLine("Enter value:");
                input = Console.ReadLine();    
                // Check if user enter a value
                if (int.TryParse(input, out int x))
                {
                    // Perform the operation
                    switch (operation)
                    {
                        case 1:
                            calculator.Add(x);
                            break;
                        case 2:
                            calculator.Subtract(x);
                            break;
                        case 3:
                            calculator.Multiply(x);
                            break;
                        case 4:
                            calculator.Divide(x);
                            break;
                        default:
                            Console.WriteLine("Unknown Operation");
                            break;
                    }
                }
            }
            else // user did not enter a number
            {                    
                break;  // end the while loop
            }
        }
    }
}

Inside the loop, the last result is displayed and the user selects the operation 1-4 and types a number to use.在循环内部,显示最后的结果,用户选择操作 1-4 并键入要使用的数字。 Then use the calculator methods to do the math.然后使用计算器方法进行数学运算。 For example calculator.Add(x);例如calculator.Add(x); adds the number stored in x to the result.将存储在x中的数字添加到结果中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM