关于数组值相加求组合问题[已解决]
本帖最后由 m765555 于 2011-6-20 14:40 编辑郁闷,这代码没有任何输出呢:Global $a=["1","0.6","3","0.1","10","1.97","3","2.4","16.3","12.6","6","3","3"]
For $i=1 To 12
For $j= $i+1 To 12
For $k = $j+1 To 12
If $a[$i] + $a[$j] + $a[$k] =13.97 Then MsgBox(0,0,$a[$i] & "+" & $a[$j] & "+" & $a[$k] & "=13.97")
Next
Next
Next 本帖最后由 飘云 于 2011-6-14 12:02 编辑
这个顺序相加中,有组合相加会是13.97吗?我用14.97倒是蛮多的
另外$i也不能到12吧,它到12,那后面两变量怎么办呢?超出数组维数了呀 明白了,代码循环层数不够;Global $a=["1","0.6","3","0.1","10","1.97","3","2.4","16.3","12.6","6","3","3"]
For $i=1 To 12
For $j= $i+1 To 12
For $k = $j+1 To 12
For $p = $k +1 To 12
For $b = $p + 1 To 12
If $a[$i] + $a[$j] + $a[$k] + $a[$p] +$a[$b] =13.97 Then MsgBox(0,0,$a[$i] & "+" & $a[$j] & "+" & $a[$k]&"+" &$a[$p]& "+" & $a[$b] & "=13.97")
Next
Next
Next
Next
Next
本帖最后由 daiyu116 于 2011-6-15 15:00 编辑
回复 3# m765555
我觉得LZ应该这样去写。首先是数字不是字符串,另外,应该从数组的第一个数开始计算吧。数字我改动了一下。
Global $a=
For $i=0 To 12
For $j= $i+1 To 12
For $k = $j+1 To 12
For $p = $k +1 To 12
For $b = $p + 1 To 11
If $a[$i] + $a[$j] + $a[$k] + $a[$p] +$a[$b] =13.97 Then MsgBox(0,0,$a[$i] & "+" & $a[$j] & "+" & $a[$k]&"+" &$a[$p]& "+" & $a[$b] & "=13.97")
Next
Next
Next
Next
Next
如果求所有组合,且不考虑数据重复,可以这样
实际应用,代码可以优化以加快速度。
#include <Array.au3>
Global $a=["1","0.6","3","0.1","10","1.97","3","2.4","16.3","12.6","6","3","3"]
Global $jg
$h = 13.97
For $i = 2 To UBound($a)
$aArrayCombo = _ArrayCombinations($a, $i, ",")
For $j = 1 To UBound($aArrayCombo)-1
If js($aArrayCombo[$j]) = $h Then
$jg += 1
_ArrayAdd($jg, $aArrayCombo[$j])
EndIf
Next
;_ArrayDisplay($aArrayCombo, "iSet = " & $i)
Next
_ArrayDisplay($jg, "和为" & $h & "的可能组合如下")
Func js($n)
$t = 0
;ConsoleWrite($n&@crlf)
$b = StringSplit($n, ',')
For $k = 1 To UBound($b)-1
$t += $b[$k]
Next
Return $t
EndFunc ;==>js 本帖最后由 m765555 于 2011-6-15 18:04 编辑
P版的代码太经典了,但有点看不懂,小弟想学习一下,P版可以对每行代码给个详细的注释吗?谢谢了!非常感谢!代码的意思可以查询,但思路无法查询,请P版指导下! 这个比较好玩,借用PCBAR版主的代码也来学习一下.
#include <Array.au3>
Global $a=["1","0.6","3","0.1","10","1.97","3","2.4","16.3","12.6","6","3","3"]
local $str,$jg
$h = 13.97
For $i = 2 To UBound($a)
$aArrayCombo = _ArrayCombinations($a, $i, "+")
For $j = 1 To UBound($aArrayCombo)-1
If Execute($aArrayCombo[$j]) = $h Then $str&=$aArrayCombo[$j]&"|"
Next
Next
$jg=StringSplit(StringTrimRight($str,1),"|")
_ArrayDisplay($jg) 呵呵,不错啊 回复 4# daiyu116
数字可以是字符串形式的,在进行数学运算时,AU3会自动将之按数字处理~~ 回复 9# annybaby
哦,是这样子,学习了。
在效率上有什么不同么? 回复 10# daiyu116
如果本身是数字的话,当然用数字会比较好吧~~至少不用再判断和转换
另外,如果字符串被当作数字处理时(即参与数学运算),如果第一个字符不是数字,那么字符串被当作0来计算,如果是以数字开头的话,那么就会取前面的有数学意义的的,比如说'78.5没钱了'会当作78.5
$s1=12
$s2='20.6哈哈,我不是数字哦'
MsgBox(0,0,$s1+$s2)
论坛好像出了点问题,无法上传截图,运行结果是32.6 回复 11# annybaby
嗯,有意思,谢谢annybaby 啊~呵呵,以后多交流多指教 各位大神的代码都很强大,顶一个 学习了..顶一个 学习了,留下标记。
页:
[1]