gpt4 book ai didi

c# - 抛出异常时退出循环是否可以?

转载 作者:行者123 更新时间:2023-12-03 23:18:30 26 4
gpt4 key购买 nike

我在Hackerrank.com上解决了一个任务,问题是这样的:

You have an Array. This Array contains numbers.
Now you enter two numbers:

  • The first one describes a sum
  • The second one describes the amount of indexes (sequence length) you add together

In the end you get the amount of sequences whose sum is your defined number

For example:

Your array is [ 1, 2, 3, 4], your sum is 3 and your sequence length is 2.
Now you take the first two indexes and output the sum: [1, 2] = 3.
This is equal to your sum, so now you have found one sequence.
The next sequence is [ 2, 3 ] = 5. This is not equal to 3, so your sequence counter stays 1.
The last sequence is [3, 4] = 7. This is also not equal to 3 and in the end, you found one sequence.

我为此编写了这段代码:

static int GetSequences(List<int> s, int d, int m)
{
//m = segment-length
//d = sum

int count = 0;
int j = 0;
int k = 0;

do
{
try
{
List<int> temp = new List<int>();

for (int i = 0; i < m; i++)
{
temp.Add(s[i + k]);
}
if (temp.Sum() == d)
{
count++;
}
j++;
k++;
}
catch (ArgumentOutOfRangeException)
{
break;
}

} while (true);

return count;
}

因为我不知道我要数多少次
(例如,序列长度为 3 的 6 长度数组有 4 个序列(1,2,3 | 2,3,4 | 3,4,5 | 4,5,6)),
当索引超出范围时,我将停止 while 循环。但我不确定这个解决方案是否可以。不仅与程序速度有关,而且与代码清洁度有关。这段代码是否可以接受,还是使用 for 循环更好,例如,对于具有 3 长度序列的 6 长度数组,该循环恰好循环 4 次?

最佳答案

不推荐,不。异常应该保留给不应该发生的事情,而不是流程控制或验证。

您想要的是使用条件逻辑(if 语句)和 break 关键字。

此外,codereview.stackexchange.com 更适合此类问题。

关于c# - 抛出异常时退出循环是否可以?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59629537/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com