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(…)
更改为justelse
,因为ifarr[0]
和arr[1]
不是最大的,那么您就知道arr[2]
必须无需再做任何测试。