【问题标题】:Error: cannot convert int to string while printing array values in Console.WriteLine错误:在 Console.WriteLine 中打印数组值时无法将 int 转换为字符串
【发布时间】:2021-10-03 02:49:23
【问题描述】:

下面给出的代码给出了 b[3] 处无法从 int 转换为字符串的错误

static void Main(string[] args)
    {
        int[] b = new int[5] { 1, 7, 8, 9, 2 };
        Console.WriteLine(b[3],b[4]); 
        
    }

而下面给出的代码可以正常工作,没有任何问题

int[] b = new int[5] { 1, 7, 8, 9, 2 };
        Console.WriteLine($"{b[3]} {b[4]}");

【问题讨论】:

    标签: c# .net dsa


    【解决方案1】:

    Console.WriteLine 不太适合仅打印传递的多个参数(例如,python 中的 print does)。 Console.WriteLine 带有 2 个参数(12)的重载要求第一个参数是包含 a composite format string 的字符串,第二个参数将用于填充此格式字符串中的占位符。

    如果您想打印多个项目,您需要手动将它们组合成字符串。例如:

    • 通过string inteerpolation 如您的问题
      Console.WriteLine($"{b[3]} {b[4]}");
      
    • 使用string.Join(收藏更方便):
      Console.WriteLine(string.Join(" ", new []{ b[3], b[4]}));
      

    或使用格式字符串:

    Console.WriteLine("{0} {1}", b[3], b[4]);
    

    Console.WriteLine("{0} {1}", new object[]{b[3], b[4]}); // better used with reference types
    

    【讨论】:

      【解决方案2】:

      Console.WriteLine 需要打印一个参数。您正在传递 2 个参数。

      你可以改成:

      static void Main(string[] args)
      {
          int[] b = new int[5] { 1, 7, 8, 9, 2 };
          Console.WriteLine(b[3]);
          Console.WriteLine(b[4]);
      }
      

      或者更好:

      static void Main(string[] args)
      {
          int[] b = new int[5] { 1, 7, 8, 9, 2 };
          Console.WriteLine($"{b[3]} {b[4]}");
      }
      

      在这种情况下,我使用string interpolation 传递一个参数。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-08-10
        • 1970-01-01
        • 2020-04-01
        • 2011-10-17
        • 2014-12-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多