【问题标题】:Why is the for-loop choosing the wrong IF statement path? [closed]为什么 for 循环选择了错误的 IF 语句路径? [关闭]
【发布时间】:2019-06-17 15:49:37
【问题描述】:

所以我正在做一个在线编码挑战,并遇到了这个让我难过的问题:

这是我的代码:

 static void Main(String[] args)
        {
            int noOfRows = Convert.ToInt32(Console.ReadLine());

            for (int i = 0; i < noOfRows; i++)
            {
                string odds = "";
                string evens = "";

                //get the input word from console
                string word = Console.ReadLine();

                for (int j = 0; j < word.Length; j++)
                {
                    //if the string's current char is even-indexed...
                    if (word[j] % 2 == 0)
                    {
                        evens += word[j];                       
                    }
                    //if the string's current char is odd-indexed...
                    else if (word[j] % 2 != 0)
                    {
                        odds += word[j];
                    }                   
                }
                //print a line with the evens + odds
                Console.WriteLine(evens + " " + odds);
            }
        }

本质上,问题是要我从控制台行获取字符串并在左侧打印偶数索引字符(从 index=0 开始),然后是空格,然后是奇数索引字符。

所以当我尝试使用“Hacker”这个词时,我应该会看到该行打印为“Hce akr”。当我调试它时,我看到代码成功地将字母'H'放在左边(因为它是index = 0,因此是偶数),并将字母'a'放在右边(奇数索引)。但是当它到达字母“c”时,它没有通过第一个 IF 路径(偶数索引),而是跳过它并进入奇数索引路径,并将其放在右侧?

有趣的是,当我尝试使用“Rank”这个词时,它可以正常工作并打印出正确的语句:“Rank”,而其他词却没有。

奇怪的是我得到了不同的结果。

我错过了什么?

【问题讨论】:

  • 注意:if (someCondition) { } else if (!someCondition) { } 是多余的。您可以删除第二个if,但保留else,例如if (someCondition) { } else { }
  • if(j % 2 == 0) evens += word[j]; else odds += word[j];
  • @Cid:谢谢,有道理——因为我正在试验,我只是修改了它以尝试不同的东西来使它工作

标签: c# for-loop if-statement


【解决方案1】:

word[j] 是字符串中的一个字符j 是您要检查其均匀度的索引。

【讨论】:

  • 跟进:原来的代码仍然执行的原因是因为char可以隐式转换为整数,用于% 2检查。因此,word[j] % 2 检查字符的 ASCII 值是否为偶数。
  • @Scott Hunter:谢谢!
  • 我很想知道为什么这个答案被否决
  • @gunr2171 谢谢,很好的解释,现在很有意义
  • @Cid 谁知道它为什么被否决
【解决方案2】:

if (j%2) 应该提供正确的路径。您正在使用 if( word[j] %2) 对字符而不是索引进行模运算。最有可能对 ASCII 值使用模数。希望这会有所帮助。

【讨论】:

  • 非常感谢! @暗影之刃
【解决方案3】:

你想检查索引是否是偶数,但你比较word[j] % 2 == 0,它不是一个索引。 你应该怎么做:

if(j % 2 == 0){

}

【讨论】:

  • 非常感谢! @lior
  • 没问题!乐于助人
猜你喜欢
  • 2018-04-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多