0

我很难找出我的代码有什么问题。我正在尝试在 C# 中创建一个控制台应用程序。该程序应该要求用户输入 3 个数字。所有的数字都必须大于 0。第一个数字应该是偶数,第二个应该是整数,第三个应该是奇数。我的语法似乎是正确的,但是,当我运行程序时,它似乎忽略了 if (userInput > 0) 部分。这是我的代码:

class Program
{
    static void Main(string[] args)
    {
        try
        {
            int userInput;
            Console.WriteLine("Please enter an even number.");
            userInput = Convert.ToInt32(Console.ReadLine());
            if (userInput > 0 && !isEven(userInput))
                return;
            Console.WriteLine("Please enter a whole number.");
            userInput = Convert.ToInt32(Console.ReadLine());
            if (userInput > 0)
            Console.WriteLine("Please enter an odd number.");
            userInput = Convert.ToInt32(Console.ReadLine());
            if (userInput > 0 && isEven(userInput))
                return;
            Console.WriteLine("Congratulations!");
            Console.WriteLine("Press any key to continue.");
            Console.ReadKey();
        }
        catch { }
    }

    static bool isEven(int value)
    {
        if (value % 2 == 0)
            return true;
        else
            return false;
    }       
}

如果有人能告诉我如何正确测试这两种情况,我将永远感激不尽。谢谢。

4

4 回答 4

3

您对输入的第一个数字的要求基本上是:

该数字必须是正数和偶数。

其反面是:

如果数字不是正数,或者不是偶数,那么它是无效的。

你的支票说

如果数字是正数并且是奇数,则拒绝它

这意味着任何为零、负数甚至是有效的数字都是有效的。

我们这里有一个德摩根定律的应用。它指出:

!(A && B)

相当于

!A || !B

因此,如果有效数字是偶数正数,则无效数不是偶数或非正数(非正数小于或等于零)

于 2014-02-14T18:11:43.317 回答
1

问题:您正在使用逻辑与检查一个有效场景和其他无效场景。

解决方案:您需要将两种无效场景与逻辑 OR 一起使用。

如果违反以下任何一项规则,则不应按照您的要求程序进行:

一个。用户输入应该 > 0
b。用户输入应该是奇数、整数和偶数

1. 替换这个:

if (userInput > 0 && !isEven(userInput))

有了这个:

if (userInput <= 0 || !isEven(userInput))

2.替换这个:

if (userInput > 0 && isEven(userInput))

有了这个:

if (userInput <= 0 || isEven(userInput))
于 2014-02-14T18:08:15.577 回答
0

查看

if (userInput <= 0 || !isEven(userInput))
    return;

由于您想在数字不是正数或数字不是偶数时退出。


德摩根定律告诉你如何反转一个逻辑表达式。您可以通过将每个术语替换为它的否定术语并将 AND 替换为 OR 来实现,反之亦然。

所以你也可以写

if (userInput > 0 && isEven(userInput)) {
    // The user input is ok, continue
} else {
    return;
}

userInput <= 0是 的否定userInput > 0

德摩根定律

NOT(A AND B) = NOT(A) OR NOT(B)

NOT(A OR B) = NOT(A) AND NOT(B)
于 2014-02-14T18:18:23.653 回答
0

根据您构建程序的方式,在第二个 if IE 之后可能应该有一个 return 语句:

if (userInput > 0)
    return;

但是,这仍然不能解决您可能想说的是:

if (userInput <= 0)
    return;

或者更直接地从英文翻译:

if (!(userInput > 0))
    return;

正如其他人所提到的,这种符号变化也适用于您的其他 if 语句。

于 2014-02-14T18:22:08.750 回答