简体   繁体   English

基本的C#if语句查询

[英]Basic c# if-statement inquiry

I need to input 3 numbers, and then output the highest & lowest of the 3 numbers using IF commands. 我需要输入3个数字,然后使用IF命令输出3个数字中的最高和最低值。 I have everything working, except I'm getting 1 largest number (correct) and 3 outputs of the lowest number (incorrect). 我一切正常,除了我得到了1个最大的数字(正确)和3个输出的最小数字(错误)。 Now I totally understand why they're all being displayed, I just do not know how to fix it. 现在我完全理解为什么它们都被显示了,我只是不知道如何解决。 My code, once the integers have been defined by user input, is as follows: 一旦用户输入定义了整数,我的代码如下:

if (num1 > num2 && num1 > num3)
{
    Console.WriteLine("Largest Number: " + num1);
}

if (num2 > num3)
{
    Console.WriteLine("Smallest Number: " + num3);
}
else
{
    Console.WriteLine("Smallest Number: " + num2);
}

and then duplicated 3 times, switching the respective integers. 然后重复3次,分别切换整数。 I understand what the issue is, it's that the second if command is correct for all 3 scenarios. 我了解问题出在哪里,这是第二个if命令对于所有3种情况都是正确的。 I just... don't know how to fix it. 我只是...不知道如何解决。 I feel like I just need to join these two if statements together somehow but I'm unsure how to do this, or if it's even possible. 我觉得我只需要以某种方式将这两个if语句连接在一起,但是我不确定如何执行此操作,甚至不确定是否可行。

You can, and you will have to, on many instances nest blocks. 您可以并且必须在许多实例上嵌套块。 This way, the second if will only be evaluated if the first was evaluated as true. 这样,仅当第一个被评估为true时,才会评估第二个if。

if (num1 > num2 && num1 > num3)
{
    Console.WriteLine("Largest Number: " + num1);

    if (num2 > num3)
    {
    Console.WriteLine("Smallest Number: " + num3);
    }
    else
    {
        Console.WriteLine("Smallest Number: " + num2);
    }
}

This is only to answer your most immediate problem, that is, the smallest number being displayed more than one time. 这仅是为了回答您最直接的问题,即最小的数字被显示多次。

You might encounter others, for example, as others mentioned : What if two numbers are equals ? 例如,您可能会遇到其他人,就像其他人提到的那样:如果两个数字相等怎么办?

To get the largest/lowest the best way is to have a variable to store the current max/min instead of checking every cases (permutation). 要获得最大/最低值,最好的方法是让一个变量存储当前的最大/最小值,而不是检查每种情况(排列)。

Something like 就像是

    int largest = int.MinValue;
    int smallest = int.MaxValue;

    if (num1 > largest)
        largest = num1;
    if (num2 > largest)
        largest = num2;
    if (num3 > largest)
        largest = num3;

    if (num1 < smallest)
        smallest = num1;
    if (num2 < smallest)
        smallest = num2;
    if (num3 < smallest)
        smallest = num3;

//output largest/smallest

No if statements necessary: 否, if有必要的话:

Console.WriteLine("Largest Number: " + Math.Max(Math.Max(num1, num2), num3));
Console.WriteLine("Smallest Number: " + Math.Min(Math.Min(num1, num2), num3));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM