算出这些数字是否连续.例如:"5-6-7-8-9",显示:"Consecutive&quo
本文关键字:quot 5-6-7-8-9 显示 Consecutive quo 连续 是否 例如 数字 | 更新日期: 2023-09-27 18:15:57
我正在做一个基本的字符串练习问题我的逻辑是这样的但很明显,我们不能增加像这样的字符串值temp++
在我的情况下,它的解决方案应该是什么:
Console.WriteLine("Input a few numbers separated by a hyphen : ");
var input = Console.ReadLine();
var split = input.Split('-');
var temp = split[0];
for (int i = 1; i < split.Length; i++)
{
temp++;
Console.WriteLine(temp);
if (temp == split[i])
{
Console.WriteLine("Consecutive");
}
}
你可以这样做:
static bool AreConsecutive(IReadOnlyList<int> numbers)
{
for (var i = 1; i < numbers.Count; ++i)
{
if (numbers[i] != numbers[i - 1] + 1)
return false;
}
return true;
}
你可以这样写:
Console.WriteLine("Input a few numbers separated by a hyphen : ");
var input = Console.ReadLine();
var inputParsed = input.Split('-').Select(int.Parse).ToList();
if (AreConsecutive(inputParsed))
Console.WriteLine("Consecutive");
在错误输入(不能解析为整数的字符)的情况下,这不会给出令人愉快的消息。
我强烈建议不要使用var
,当右边不能很明显地表明是什么类型。
让我用变量类型重写一下,看看是否能让问题更清楚:
Console.WriteLine("Input a few numbers separated by a hyphen : ");
string input = Console.ReadLine();
string[] split = input.Split('-');
// Think about what type this SHOULD be
string temp = split[0];
for (int i = 1; i < split.Length; i++)
{
// Considering the fact that temp is actually currently a string, why should this work?
// It's pretty obvious what "1" + 2 would mean, but what would "dog" + 1 mean?
temp++;
Console.WriteLine(temp);
// Consider the fact that these must be the same type to do "==" (or there must be an implicit typecast between them)
if (temp == split[i])
{
Console.WriteLine("Consecutive");
}
}