簡體   English   中英

如何使用 c# 中的 for 循環中的數字進行加法?

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

我是 c# 的新手,我正在嘗試制作一個計算器。 在這些代碼中,我試圖從 for 循環中的輸入中獲取值並對其進行添加。 但我做不到。 我怎樣才能做到這一點?

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);

                }
            }
        }
    }
}

您沒有在 for 循環中添加任何數字。 您正在用解析的每個數字覆蓋 NumberToMakeAddition2 的值。

在 for 循環之外定義 NumberToMakeAddition2 並將其初始化為 0。將您解析的每個數字添加到總和中。

您沒有錯誤處理,因此如果輸入的文本不是 integer,請小心。

我建議您使用int.TryParse()而不是int.Parse ,因為我們不能信任來自控制台的輸入。 您在這里唯一需要做的就是在循環外聲明一個變量,並在循環時將總和保存在該變量中。 示例代碼如下所示:

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,首先,您假設人們會進行可解析為 int 的輸入。 情況可能並非如此。 檢查並研究 int.TryParse() 。 其次,在您的循環中,您正在重新聲明一個新變量 NumberToMakeAdition2 並將解析后的值分配給它。 那里沒有添加。 您應該做的是在循環之前對其進行初始化,例如:

int sum = 0;

然后在循環中添加:

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

像這樣創建一個列表: List<int> myList = new List<int>() ,將所有用戶號碼推入。 在您的循環中,當您解析用戶條目時,請使用myList.Add(NumberToMakeAddition) 然后,在您的循環之后,您可以執行MyList.Sum() ,或者您可以遍歷您的列表並一次添加一個

我在代碼中做了一些更正。 您正在使用 = 運算符,每次將編號(需要添加)分配/存儲到變量 NumberToMakeAddition2。 所以 output 是最后輸入的數字。

對於所需的 output 或正確執行加法,需要做三件事:-

  1. 在 for 循環外聲明 NumberToMakeAddition2並設置為零。
  2. 使用 += 運算符,如果它是有效的 int,則在 NumberToMakeAddition2 中添加每個輸入/輸入的數字。 在后台是這樣的:-

NumberToMakeAddition2 += 輸入的數字;

與以下相同

NumberToMakeAddition2 = NumberToMakeAddition2 + 輸入的數字;

  1. 異常處理:- 輸入也可以作為字符串輸入,也可以輸入無效數字,如特殊字符或任何字符串,因此系統/代碼將引發異常和崩潰,但在此要求中,系統/代碼應給出正確的消息並忽略無效。 為此,請使用 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.

使用系統; 使用 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");
               }
                
            }
        }
    }
}

這是C#並且高度面向對象,您將其視為腳本並將所有代碼都放在Main()下,這是對自己的傷害。

C#考慮數據 model。 如何定義包含我不需要的信息的對象。 在這個例子中我想做一個計算器,所以我設計了一個 class 來保存計算器的結果,並且可以對這個結果進行基本的操作。

數據 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;
    }
}

上面的很簡單。 有四種方法可以修改結果,以及一種構造函數來初始化數據。

程序

然后,實際程序應定義數據 model 並對其進行操作。 當用戶可以 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
            }
        }
    }
}

在循環內部,顯示最后的結果,用戶選擇操作 1-4 並鍵入要使用的數字。 然后使用計算器方法進行數學運算。 例如calculator.Add(x); 將存儲在x中的數字添加到結果中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM