C# 返回数组中的最大数字

C# 返回数组中的最大数字,c#,C#,在我的代码中,&&的最佳更改是什么?我真的不知道如何修复它。以下是我目前掌握的代码: using System.Collections; using System.Collections.Generic; using UnityEngine; public class A3 : MonoBehaviour { int[] arr = new int[3] { -7, 2, 6 }; int reBig () { if (arr[0] > arr

在我的代码中,
&&
的最佳更改是什么?我真的不知道如何修复它。以下是我目前掌握的代码:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class A3 : MonoBehaviour
{

    int[] arr = new int[3] { -7, 2, 6 };

    int reBig ()
    {
        if (arr[0] > arr[1] && arr[2])
        {
            return (arr[0]);
        }
        else if (arr[1] > arr[0] && arr[2])
        {
            return (arr[1]);
        }
        else if (arr[2] > arr[0] && arr[1])
        {
            return (arr[2]);
        }

    } 

    // Start is called before the first frame update
    void Start()
    {
        print(reBig()); 
    }

    // Update is called once per frame
    void Update()
    {

    }
}

arr[0]>arr[1]&&arr[2]
并不是你认为的意思。你在使用它时,好像它意味着“
arr[0]
大于
arr[1]
arr[2]
”,但它实际上意味着“
arr[0]
大于
arr[1]
,而
arr[2]
是真实的”。要得到您想要的含义,您需要这样编写:
arr[0]>arr[1]&&arr[0]>arr[2]
。其他两条类似的线也是如此。

试试
arr.Max()@ja72这看起来像是家庭作业,他不可能被允许使用它。是的,它起作用了!但现在我得到了cs0161错误。你知道为什么吗?@Ацццжжжжжж编译器不够聪明,无法知道3个
if
块中的一个必须为真。要修复它,只需将最后一个
else if(…)
更改为just
else
,因为if
arr[0]
arr[1]
不是最大的,那么您就知道
arr[2]
必须无需再做任何测试。