条件语句表现不如预期。

我的数学老师有一道奇妙的万圣节额外题目:

每个字母代表一个数字2-9,而您需要以下问题:

trick + or = treat

我决定要找出问题的所有可能解决方案(以打动他),所以我决定编写一个电脑程序来告诉我所有的答案。下面是我的代码:

local function checkAdd()

local trick =k+(10*c)+(100*i)+(1000*r)+(10000*t) local _or =r+(10*o) local treat = t+(10*a)+(100*e)+(1000*r)+(10000*t) if trick + _or == treat then print(trick) print(" ".._or) print(treat) print(t) print(r) print(i) print(c) print(k) print(o) print(e) print(a) end --print("end") timer.performWithDelay(1,newNumbers) end local function checkNumbers8() if t or r or i or c or k or o or e or a == "9" then checkAdd() else newNumbers() end end

local function checkNumbers7() if t or r or i or c or k or o or e or a == "8" then checkNumbers8() else newNumbers() end end

local function checkNumbers6() if t or r or i or c or k or o or e or a == "7" then checkNumbers7() else newNumbers() end end

local function checkNumbers5() if t or r or i or c or k or o or e or a == "6" then checkNumbers6() else newNumbers() end end

local function checkNumbers4() if t or r or i or c or k or o or e or a == "5" then checkNumbers5() else newNumbers() end end

local function checkNumbers3() if t or r or i or c or k or o or e or a == "4" then checkNumbers4() else newNumbers() end end

local function checkNumbers2() if t or r or i or c or k or o or e or a == "3" then checkNumbers3() else newNumbers() end end

local function checkNumbers() if t or r or i or c or k or o or e or a == "2" then checkNumbers2() else newNumbers() end end

function newNumbers() t = mRandom(2,9) r = mRandom(2,9) i = mRandom(2,9) c = mRandom(2,9) k = mRandom(2,9) o = mRandom(2,9) e = mRandom(2,9) a = mRandom(2,9) checkNumbers() end

newNumbers()

*请注意,在checkAdd函数中,我调用了timer.performwithdelay函数(等待1毫秒才调用该函数)。这是因为如果我不带函数调用地运行此代码,我会得到栈溢出错误。因此,我把我的代码放入我用于应用程序开发的框架中,该框架具有timer.performwithdelay调用,并将其实现到我的代码中,以便电脑不会太忙碌并导致溢出错误。

我得到以下打印语句:

97552
27
97579
9
7
5
5
2
2
5
7

和:

49325
59
49384
4
9
3
2
5
5
3
8

我发现有些字母等于其他字母! 而且并没有使用所有数字2-9!我的代码是错的吗?我测试以查看是否使用了2-9中的每个数字。

点赞
用户1442917
用户1442917

我认为有两个主要问题。我没有看到函数mRandom,但我假设它返回一个_数字_,而您正在将其与_字符串_进行比较。数字2与字符串'2'不同,因此2 == '2'将返回false

第二个问题是(似乎)您正在尝试比较变量中的任一一个是否具有特定值,但您不能这样做if a or b == 2 then意思是:如果ab等于2,则执行。为此,您需要编写if a == 2 or b == 2。您所拥有的被评估为:如果a被评估为true(这是当它不是nilfalse时)或b等于2。

2014-10-29 22:48:40