如何在和数之间添加“ +”号?

时间:2019-02-06 13:04:25

标签: c#

我正在尝试构建一个基本的c#应用程序,该应用程序通过控制台添加数字,但是我无法让该程序在每个数字之间显示加号。

public class Program
{
    public static void Main(string[] args)
    {
        Console.Clear();

        string calculation = "";
        double sum = 0.0;

        foreach (string arg in args)
        {
            if (string.IsNullOrEmpty(calculation)) calculation = arg;
            else calculation =  " + " + args;
            sum = sum + Convert.ToDouble(arg);
        }
        Console.WriteLine(sum + calculation);
    }
}

4 个答案:

答案 0 :(得分:1)

查询数据(在您的情况下为args数组时),请尝试避免循环并使用Linq:

    using System.Linq;

    ...

    public static void Main(string[] args) {
      Console.Clear();

      // Combine all args with " + "
      string calculation = string.Join(" + ", args);

      // Parse each arg within args then Sum them
      double sum = args.Select(arg => double.Parse(arg)).Sum();

      // Let's use string interpolation to make code be more readable
      Console.WriteLine($"{calculation} = {sum}");
    }

如果您想要好的旧循环解决方案

    Console.Clear();

    // Appending String in a loop can be time consuming
    // We have a special type for this - StringBuilder
    StringBuilder calculation = new StringBuilder();
    double sum = 0.0;

    foreach (string arg in args)
    {
        if (calculation.Length > 0)
            calculation.Append(" + "); 

        calculation.Append(arg);

        sum = sum + Convert.ToDouble(arg);
    }

    Console.WriteLine($"{sum} {calculation.ToString()}");

答案 1 :(得分:0)

else calculation +=  " + " + args;

'='被分配

'+ ='是附加的

答案 2 :(得分:0)

由于计算不会为空(您在循环之前将其初始化),因此可以使用三元运算添加WITH cte AS ( SELECT ROW_NUMBER() OVER (ORDER BY Deal, [Date]) id, Deal, [Date], [Sum], SUM([Sum]) OVER(PARTITION BY Deal ORDER BY [Date]) AS Debt_balance FROM t ) SELECT a.Deal, SUM(a.Sum) AS NET_Debt, isnull(max(b.date), min(a.date)), datediff(day, isnull(max(b.date), min(a.date)), getdate()) FROM cte as a LEFT OUTER JOIN cte AS b ON a.Deal = b.Deal AND a.Debt_balance <= 0 AND b.Id=a.Id+1 GROUP BY a.Deal HAVING SUM(a.Sum) > 0 和条件arg(请注意," + "而不是{{ 1}}进行分配):

+=

但是可以在循环之前使用=来写同样的东西(请注意calculation += (string.IsNullOrEmpty(calculation) ? "" : " + ") + arg; 数组的使用,而不是循环中单个string.Join的使用):

args

对于参数1、2、3,这将创建如下字符串:arg。 对于空的args,这只会返回一个空字符串

答案 3 :(得分:0)

您可以使用Join()" + "字符串重建字符串数组。

// build the calculation string
string calculation = String.Join(" + ", args);
double sum = 0.0;
// calculate
foreach (string arg in args)
{
    sum += Convert.ToDouble(arg);
}

例如:

String[] arr = {"42", "69", "403"};
string result = String.Join(" + ", arr);
Console.WriteLine(result);

输出:

  

42 + 69 + 403