2017-04-25 62 views
-2

我想一些幫助,我在寫代碼計數可能的組合代碼。我需要寫一個循環計數程序中的一個號碼,我輸入的組合數,它需要檢查我有多少組合能做到的,用數字10,5,2,1。製作只用循環

例如,如果我輸入5有4個組合 - (5 | 2 2 1 | 2 1 1 1 | 11111)。

我試圖做一些循環,但我不知道如何使它工作,我想使用一個while循環,但我不知道如何計算組合,真的非常感謝任何幫助在物。

這裏是我到目前爲止的代碼

#include <stdio.h> 

void main() 
{ 
    printf("enter a number\n"); 
    int num, i, m = 2, counter = 0, g = 2; 
    scanf_s("%d", &num); 

    for (i = 1; m > 1 ; i++) 
    { 
     m = num - (5 * i); 
     for (i = 1; g > 1; i++) 
     { 
      counter++; 
      g= m - (2 * i); 
     } 
    } 

    printf("The counter is %d\n", counter); 
} 

我的總體思路是從底層做起。例如,如果我輸入10, 我得到10 -2然後計數器計數1,則另一個-2從8(10-2),並將其重新計數,並且當我輸入像5更高數目的我想一個循環,以除去10 - 5 = 5,然後進入下一個循環並計數5 2 2 1,依此類推...

我真的很感謝一些幫助,謝謝!

+0

'int main(void)' –

回答

0

這是一種策略,你可以使用。

假設輸入是N

首先,你可以說:「有多少組合是有,如果我用10正好一次

這將是:

combinations = calculate_combinations_when_only_using_5_2_1(N-10); 

然後你就可以說:「有多少組合是有,如果我用10正好兩個時間

這將是:

combinations = calculate_combinations_when_only_using_5_2_1(N-20); 

下一次使用10正好3倍等。

這可以變成:

int calculate_combinations_which_includes_10(int N) 
{ 
    int result = 0; 
    while(N >= 10) 
    { 
     result += calculate_combinations_when_only_using_5_2_1(N-10); 
     N = N - 10; 
    } 
    return result; 
} 

用類似的方法,你可以編寫返回,其中包括5個組合的數量和另一個函數的函數返回,其中包括組合數2.只要記住:

int calculate_combinations_which_includes_1(int N) 
{ 
    return 1; // Always exactly 1 combination in this case 
} 

現在你只需要calculate_combinations_when_only_using_5_2_1calculate_combinations_when_only_using_2_1我將離開你要弄清楚。

+0

非常感謝,我會盡力的。 –