简体   繁体   English

Swift(和一般编程)的新手。 为什么我的代码调用了错误的操作?

[英]New to Swift (and programming in general). Why is my code calling the wrong action?

I'm a total newbie, so pardon me if this is an annoying question.我是一个新手,如果这是一个烦人的问题,请原谅我。 I am just practicing and am wondering why this code is printing "Almost perfect. Give it another try," when it should be printing "Well. you got one correct".我只是在练习,想知道为什么这段代码会打印“几乎完美。再试一次”,而它应该打印“嗯。你猜对了”。 Any help would be much appreciated任何帮助将非常感激

var subjectOne = true
var subjectTwo = false
var subjectThree: Int = 5
func shout(subjectOne: Bool, subjectTwo: Bool, subjectThree: Int){
    if subjectOne && subjectTwo && subjectThree >= 25{
        print("HIGH SCORE!")
    }
    else if subjectOne || subjectTwo && subjectThree >= 10{
        print("Almost perfect. Give it another try!")
    }
    else if subjectOne && subjectTwo && subjectThree >= 10{
        print("There ya' go!")
    }else if !subjectOne && !subjectTwo && subjectThree >= 10{
        print("Well, you got a high enough number at least!")
    }else if subjectOne || subjectTwo && subjectThree < 10{
        print("Well, you got one correct")
    }else if !subjectOne && !subjectTwo && subjectThree < 10{
        print("You fail at life!")
    }else if subjectOne || subjectTwo && subjectThree >= 25{
        print("Almost a high score. Keep going, you got this!")
    }
}
shout(subjectOne: subjectOne, subjectTwo: subjectTwo, subjectThree: subjectThree)

This is happening because your first else if clause is evaluating to true due to order of operations:发生这种情况是因为您的第一个 else if 子句由于操作顺序而被评估为 true:

else if subjectOne || subjectTwo && subjectThree >= 10

evaluates from left to right, so your code first checks if subjectOne is true.从左到右计算,因此您的代码首先检查subjectOne是否为真。 Because it is indeed true, and an ||因为它确实是真的,而且|| (or) comes next, your code no longer needs to evaluate the rest of the expression because it already evaluates as true. (或)接下来,您的代码不再需要评估表达式的 rest,因为它已经评估为真。

You might have meant to write that clause this way instead:您可能本来打算以这种方式编写该子句:

else if (subjectOne || subjectTwo) && subjectThree >= 10

This would evaluate to false because thanks to the parenthesis, your code knows that it must evaluate both sides of the expression (subjectOne or subjectTwo) AND subjectThree must be greater than or equal to ten.这将评估为 false,因为由于括号,您的代码知道它必须评估表达式的两侧(subjectOne 或 subjectTwo)并且 subjectThree 必须大于或等于 10。

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

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