算出数字是否连续。例如,“5-6-7-8-9”,显示:“连续”;否则,显示“不连续”

时间:2016-11-02 21:40:44

标签: c#

我正在做一个基本的字符串练习问题,我的逻辑是这样的,但是显而易见的是,在我的情况下,我们不能像这个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");
    }
}

2 个答案:

答案 0 :(得分:1)

你可以这样做:

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");

如果输入错误(不会解析为整数的字符),这将不会给出令人愉快的消息。

答案 1 :(得分:0)

我强烈建议不要使用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");
    }
}