C# 如果循环未执行,则返回Else
我在C# 如果循环未执行,则返回Else,c#,if-statement,C#,If Statement,我在c 中为我的项目编写了这段代码,当我尝试执行这段代码时,我会得到-ve个数字。我不想要一个小于零的数字。这就是为什么我在其中添加了else if循环。但它仍然不起作用。请帮忙 if (myString.Contains(input)) { int pos1 = myString.IndexOf(input); int tpos = pos - pos1; if (tpos < 20) { MessageBox.Show("Y
c
中为我的项目编写了这段代码,当我尝试执行这段代码时,我会得到-ve个数字。我不想要一个小于零的数字。这就是为什么我在其中添加了else if
循环。但它仍然不起作用。请帮忙
if (myString.Contains(input))
{
int pos1 = myString.IndexOf(input);
int tpos = pos - pos1;
if (tpos < 20)
{
MessageBox.Show("You're Safe", "Important Info", MessageBoxButtons.OK, MessageBoxIcon.Information);
MessageBox.Show(tpos.ToString());
}
else if (tpos < 0)
{
MessageBox.Show("You are Vulnerable", "Critical Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
else
{
MessageBox.Show("You are Vulnerable", "Critical Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
if(myString.Contains(输入))
{
int pos1=myString.IndexOf(输入);
int tpos=pos-pos1;
如果(tpos<20)
{
MessageBox.Show(“您很安全”,“重要信息”,MessageBoxButtons.OK,MessageBoxIcon.Information);
Show(tpos.ToString());
}
否则如果(tpos<0)
{
显示(“您易受攻击”,“严重警告”,MessageBoxButtons.OK,MessageBoxIcon.Warning);
}
其他的
{
显示(“您易受攻击”,“严重警告”,MessageBoxButtons.OK,MessageBoxIcon.Warning);
}
}
将else if
移动到if
上方,如下所示:
if (tpos < 0)
{
MessageBox.Show("You are Vulnerable", "Critical Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
else if (tpos < 20)
{
MessageBox.Show("You're Safe", "Important Info", MessageBoxButtons.OK, MessageBoxIcon.Information);
MessageBox.Show(tpos.ToString());
}
if(tpos<0)
{
显示(“您易受攻击”,“严重警告”,MessageBoxButtons.OK,MessageBoxIcon.Warning);
}
否则,如果(tpos<20)
{
MessageBox.Show(“您很安全”,“重要信息”,MessageBoxButtons.OK,MessageBoxIcon.Information);
Show(tpos.ToString());
}
在您的代码中,如果一个数字是负数,则它满足第一个
if
条件,因此从未进入else if
条件。现在,如果一个数字是负数,它将在第一个条件本身中被检查 逆转条件。对于小于零的数字,第一个条件始终为真。如果一个值小于0,你不认为它也会小于20吗?我现在刚得到答案。:-)你可能想改变你最后一句话中的一些词…;)