如何在c#中对for循环中的数字进行加法运算

  • 本文关键字:数字 运算 中对 循环 for 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将您解析的每个数字添加到总和中。

您没有错误处理,所以如果输入的文本不是整数,请小心。

Cihan,首先,你假设人们会做出可解析为int的输入。但事实可能并非如此。请检查并研究int.TryParse((。其次,在循环中,您将重新定义一个NEW变量NumberToMakeAdition2,并将解析后的值分配给它。你应该做的是在循环之前初始化它,比如:

int sum = 0;

然后在循环中添加:

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

我建议您使用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}");
}

创建一个列表,如下所示:List<int> myList = new List<int>(),将所有用户号码推送到。在循环中,解析users条目时,请使用myList.Add(NumberToMakeAddition)。然后,在循环之后,您可以执行MyList.Sum(),或者您可以循环浏览您的列表并一次添加一个

我在代码中做了一些更正。您使用的是=运算符,它每次都将/存储编号(需要添加(分配给变量NumberToMakeAddition2。所以输出是最后输入的数字。

对于所需的输出或添加的正确实现,需要做三件事:-

  1. 在for循环外声明NumberToMakeAddition2并设置零
  2. 如果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#中,考虑一个数据模型。如何定义包含所需信息的对象。在这个例子中,我想制作一个计算器,所以我设计了一个类来保存计算器的结果,并可以对这个结果执行基本操作。

数据模型

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

以上内容非常简单。有四个方法可以修改结果,还有一个构造函数可以初始化数据。

程序

然后,实际的程序应该定义数据模型并对其进行操作。当用户可以选择下一个操作时,我选择了一个无限循环,只需按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中的数字与结果相加。

最新更新