【问题标题】:Converting errors转换错误
【发布时间】:2021-12-20 20:50:46
【问题描述】:

我需要一些帮助来解决我在 Visual Studio 中收到的 C# 错误。他们声明不能将字符串转换为 int 或不能将 int 转换为 char。请问有人可以帮助我吗?

        Console.WriteLine(" The largest value in the array is ", numberArray, maximumIndex, "located at array index" + maximumIndex);

        //Loop through the two arrays and print the integer from integer array followed by the corresponding value from the string array
        Console.WriteLine(" The numbers were: ");
        for (int i = 0; i < numberArray.Length; i++)

            Console.WriteLine(numberArray[i], " is ", stringArray[i]); **Getting error for "numberArray"-Cannot convert 'int' to 'char; Getting error for "is"-Cannot convert string to int; Getting error for "stringArray"-Cannot convert string to int**

【问题讨论】:

  • 在这些写行中使用 + 而不是逗号

标签: c# arrays function


【解决方案1】:

C# 方法
尽管 (,) 运算符可以在 python 或其他一些语言中使用,但 (,) 运算符并不是控制台中真正的 C# 语法。[method] 参数。

解决方案
您可以使用这些方法中的任何一种,这完全取决于偏好。我会将它们从我最喜欢的方法到其他可能的方法进行排名:

Console.WriteLine($"{numberArray[i]} is {stringArray[i]}");
// Example output: 1 is 2

这是我认为最干净的解决方案。但另一个是使用 Concatination

Console.WriteLine(numberArray[i] + " is " + stringArray[i]);
// Example output: 1 is 2

希望这会有所帮助。存在更多处理此主题的方法,但目前这两种方法值得告诉您,想不出更舒适的版本,但我确信它们存在。

【讨论】:

  • 谢谢,成功了!
  • 没有括号是合法的:定义是for(...) statement;,其中语句是单数。这种语句的一个示例是复合语句:{,0 或多个语句,}。但是,是的,就风格而言,最好始终包含那些{ },这样就可以清楚地知道什么属于那个“for”,什么不属于
  • 我将编辑答案。感谢您的提醒
【解决方案2】:

你需要在 console.writeline 中做 + 而不是 ,

【讨论】:

  • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
【解决方案3】:

我修改了你的代码如下;

   public static void Main(string[] args)
        {
            int[] numberArray = {1, 5, 10};
            var maximumIndex = 2;

            Console.WriteLine("The largest value in the array is {0} {1} located at array index{2}", string.Join(",", numberArray), maximumIndex, maximumIndex);
        }

输出:数组中最大值为 1,5,10 2 位于数组 index2 处

参考Interpolated String

【讨论】:

    猜你喜欢
    • 2012-05-07
    • 1970-01-01
    • 1970-01-01
    • 2017-08-20
    • 1970-01-01
    • 2013-11-15
    • 1970-01-01
    相关资源
    最近更新 更多