首页 > 解决方案 > 为什么 for 循环选择了错误的 IF 语句路径?

问题描述

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

这是我的代码:

 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”,而其他词则不然。

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

我错过了什么?

标签: c#for-loopif-statement

解决方案


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


推荐阅读