簡體   English   中英

在Visual Basic中,如何確定一組5個數字加起來是否等於15個?

[英]How can I find if a set of 5 numbers add up to 15 in visual basic?

我的計算機班的一項作業是查找是否有一組5中的任何數字加起來等於15,如果它們確實得分了。 我無法弄清楚如何通過將5個數字組成一組隨機數來得出多個特定數字。 他們有特定於此的算法嗎? 而且它必須用Visual Basic編寫。

您正在尋找的算法稱為BackTracking 由於這是家庭作業,因此我不會花時間提供代碼。 這個想法是這樣的。

  • 只要它們的總和小於15,就遞歸地取數字
  • 如果精確到15,那么確定,您找到了解決方案
  • 如果超過15,則返回上一步並取另一個數字
  • 繼續直到所有變體完成

在5個數字的情況下,我只是蠻力嘗試所有32種可能的組合。

這是此任務的一些可能的偽代碼:

input = Array of 5 random integers (starting with index 0)
onoff = new Array of 5 integers (starting with index 0), initialized to 0

loop
  // Create all possible combinations of 0 and 1 in onoff Array
  // Hint: This is the same as counting up a binary number and looking at the bits.
  onoff[0] = onoff[0]+1
  for i=0 to 3
    if onoff[i] > 1
      onoff[i] = 0
      onoff[i+1] = onoff[i+1] + 1

  if onoff[4] > 1
    break loop

  // Create sum for given combination
  sum = 0
  for i=0 to 4
    sum = sum + onoff[i]*input[i]

  if sum = 15
    output "Found value set"
    for i=0 to 4
      if onoff[i] = 1
        output " "+input[i]

轉換為VB仍然是家庭作業:-)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM