如何创建一个 if 语句来询问其中包含 or 的求和
How to create an if statement to ask an summation with an or in it
我想请电脑计算
if 1 or 2 + 2 or 3 + 4 or 5 == 6{
// do this
}
它会遍历组合并在第一个数字之间找到它是 1 然后是 2 然后是 3 然后等于 6 我怎么能在代码中做到这一点?
不太清楚你要做什么,但这是我根据你的最新评论做出的最佳猜测。
给定一个表达式列表,其中是否有一个等于 6?
let expressions = [ 1, 2 + 2, 3 + 4, 5, 6 ]
for expression in expressions {
if expression == 6 {
println("found the number 6!")
break
}
}
如果任何表达式等于 6,上面将打印 "found the number 6!",在此示例中,数组中的最后一个条目是 6,因此它将打印 "found the number 6!"
我认为您要问的问题是:给定列表 [1,2]
、[2,3]
和 [3,4]
,这些值的哪些组合总和为 6。如果是,你只想对它们求和并检查。
let xs = [1,2]
let ys = [2,3]
let zs = [3,4]
func combine<T,U,V>(xs: [T], ys:[U], zs:[V]) -> [(T,U,V)] {
var result = [(T,U,V)]()
for x in xs {
for y in ys {
for z in zs {
result.append(x,y,z)
}
}
}
return result
}
let combinations = combine(xs, ys, zs)
.filter { (x, y, z) in (x + y + z) == 6 }
我想请电脑计算
if 1 or 2 + 2 or 3 + 4 or 5 == 6{
// do this
}
它会遍历组合并在第一个数字之间找到它是 1 然后是 2 然后是 3 然后等于 6 我怎么能在代码中做到这一点?
不太清楚你要做什么,但这是我根据你的最新评论做出的最佳猜测。
给定一个表达式列表,其中是否有一个等于 6?
let expressions = [ 1, 2 + 2, 3 + 4, 5, 6 ]
for expression in expressions {
if expression == 6 {
println("found the number 6!")
break
}
}
如果任何表达式等于 6,上面将打印 "found the number 6!",在此示例中,数组中的最后一个条目是 6,因此它将打印 "found the number 6!"
我认为您要问的问题是:给定列表 [1,2]
、[2,3]
和 [3,4]
,这些值的哪些组合总和为 6。如果是,你只想对它们求和并检查。
let xs = [1,2]
let ys = [2,3]
let zs = [3,4]
func combine<T,U,V>(xs: [T], ys:[U], zs:[V]) -> [(T,U,V)] {
var result = [(T,U,V)]()
for x in xs {
for y in ys {
for z in zs {
result.append(x,y,z)
}
}
}
return result
}
let combinations = combine(xs, ys, zs)
.filter { (x, y, z) in (x + y + z) == 6 }