c# - 为什么 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”,而其他词则不然。
奇怪的是我得到了不同的结果。
我错过了什么?
解决方案
word[j]
是字符串中的一个字符;j
是您要检查其均匀性的索引。
推荐阅读
- python-3.x - 使用 Cython 和外部多线程 C 库时的未定义行为
- android - 如何让安卓应用只运行后台服务,不能启动?
- javascript - 通过谷歌表格发送电子邮件的谷歌脚本冗余措施失败
- c++ - 在 C++ 中复制 __PRETTY_FUNCTION__ 的行为
- mysql - 跨多个表优化 INNER JOIN
- c# - IIS 如何知道如何启动 .NET Web 应用程序
- c# - 从 Azure Function .Net 调用没有 DNS 条目的 URL
- python - ImportError:无法导入名称“阶乘”
- c# - 为什么在特定环境下认证过程中调用 api token 会失败?(400 错误)
- excel - VBA 提取两个字符之间的字符串