c# - 我无法返回结果,也无法从函数的主函数中获取值
问题描述
问题:
让函数 ClosestEnemy(arr) 获取存储在 arr 中的数字数组,并从数组中 1 所在的位置返回您必须向左或向右移动才能到达由 2 表示的敌人的空格数。例如:如果 arr 是 [0, 0, 1, 0, 0, 2, 0, 2] 那么你的程序应该返回 3 因为最近的敌人 (2) 距离 1 3 个空格。数组将包含任何数字0 和 2,但只有一个 1。它也可能根本不包含任何 2,在这种情况下,您的程序应该返回 0。
我的问题Console.Readline()
和 return
。我不知道正确使用。
我遇到了这个错误,我在代码上添加了注释行
CS1503 C# 参数 1:无法从 'int' 转换为 'int[]'
CS0165 C# 使用未分配的局部变量“结果”
例子:
输入:新的 int[] {1, 0, 0, 0, 2, 2, 2}
输出:4
输入:新 int[] {2, 0, 0, 0, 2, 2, 1, 0}
输出:1
public static int ClosestEnemy1(int[] arr)
{
int result;
int counterright = 0;
int counterleft = 0;
int locationleft = 0;
int location1 = 0;
int locationright = 0;
int rightclosest;
int leftclosest;
int i;
// code goes here
for(i = 0; i < arr.Length; i++)
{
if (arr[i] == 1)
{
location1 = i;//1'in konumu belirlendi
}
}
//sağa kontrol et
while (arr[i]!= '\0' )//saga bak
{
i = location1;
i++;
if (arr[i] == 2)
{
counterright = 1;
locationright = i;
break;
}
}
for (i = location1; i >= 0; i--)
{
if (arr[i] == 2)
{
counterleft = 1;
locationleft = i;
break;
}
}
if(counterright == 0 && counterleft == 0)
{
result=0;
}
if(counterright == 0 && counterleft == 1)
{
result = location1 - locationleft;
}
if(counterright == 1 && counterleft == 0)
{
result = locationright - location1;
}
if(counterright == 1 && counterleft == 1)
{
leftclosest = location1 - locationleft;
rightclosest = locationright - location1;
if (leftclosest > rightclosest)
{
result = leftclosest;
}
else
{
result= rightclosest;
}
}
return result; //it's error!!!!!!!
}
static void Main()
{
// keep this function call here
Console.WriteLine(ClosestEnemy1(Convert.ToInt32(Console.ReadLine())));//it's errorr!!!!
}
解决方案
在您的代码中尝试这些更正:
1) 将输入类型更改为字符串 : public static int ClosestEnemy1(string inputString)
,确保您留下评论以供用户输入,如下所示:1, 0, 0, 0, 2, 2, 2
2)在函数内部int arr[]
由String.Split():
string[] stringNumbers = inputString .Split(',');
int[] arr = Array.ConvertAll(stringNumbers, s => int.Parse(s));
3)更改此行:
int result=0;
将默认值分配给result
.
4) 分配i=0
或者你之前认为更好的,因为最后分配的值i
是7
,它会出错。
//sağa kontrol et
i = 0;
while (arr[i] != '\0')//saga bak
5) 在 main() 函数中你得到控制台结果后,放一个Console.ReadKey();
给你看结果。
推荐阅读
- sql-server - 如何使用多个参数成功进行子查询
- rust - 如何处理 RUST 中未解决的导入“具体”问题
- linux - 如何从终端中的类似文件中选择一个文件(通过 tmux)
- html - 如何强制文本离开 div 但仍留在视口内
- json - 为什么 AllowedCommonJsDependencies 抛出错误
- mysql - “错误代码:1192。由于您有活动的锁定表或活动事务,因此无法执行给定的命令。” 即使在我添加了 UNLOCK TABLES
- linux - 中断句柄
- javascript - ReactJS - 多个元素共享相同的状态
- python - OpenAI, Python, 删除文件
- sql-server - 无法更新包含捷克字母的 nvarchar(50)