2013-03-19 56 views
0

我想製作一個過濾器,只在屏幕上打印我想要的數據。以下是我正在談論的內容:自定義過濾器功能不會產生預期的輸出

Cost* FilterSum(Controller* ctrl, int n) 
{ 
    int i; 
    DynamicVector* CostList=getAll(ctrl->repo); 
    for(i=0;i<getLen(CostList);i++) 
    { 
     Cost* c=getElementAtPosition(CostList,i); //returns the element on one position 
     if((c->sum)<n) 
     { 
      return c; //if the element(Cost in my case) has the sum<20 return it 
     } 
    } 


return 0; 
} 

所以,我將Dynamic Array與Costs作爲元素。如果成本總和小於n(n由鍵盤給出),我只想在屏幕上打印這些成本。 :) 這是在控制檯打印功能:

void PrintCost(Cost* c) //this function prints one cost 
{ 
    printf("\nID: %d\n", getID(c)); 
    printf("Day: %s\n", getDay(c)); 
    printf("Type: %s\n", getType(c)); 
    printf("Sum: %d\n\n", getSum(c)); 
} 

void PrintCosts(Console* console) //this one prints all the costs in the list 
{ 
    DynamicVector* CostList=getAllCosts(console->ctrl); 
    if (getLen(CostList)) 
    { 
     int i; 
     for(i=0;i<getLen(CostList);i++) 
     { 
      Cost *c=(Cost*)getElementAtPosition(CostList,i); 
      PrintCost(c); 
     } 

    } 
    else printf("No cost in the list!"); 
} 

,這裏是從控制器控制檯呼叫功能:

void FilterCostsBySum(Console* console) 
{ 
    int n; 
    printf("See the costs that have the sum less than: "); 
    scanf("%d",&n); 
    Cost* c = FilterSum(console->ctrl,n); 
    PrintCost(c); 
} 

現在,這裏談到的問題。如果星期一的總數= 10,星期五的總數= 20,星期六的總數= 40,我想只打印總數爲< 30的日期,它只是打印星期一,就是這樣,它也不打印星期五。我在哪裏做錯了?在控制器的FilterSum函數中,我返回c?我嘗試了一切,它根本沒有用......也許你可以幫助我! :)

+1

*咳嗽*代碼審查*咳嗽* – 2013-03-19 18:14:00

回答

1
if((c->sum)<n) 
    { 
     return c; //if the element(Cost in my case) has the sum<20 return it 
    } 

return聲明打破了環和退出FilterSum功能,所以功能只是返回其符合條件的第一Cost。您應該將其更改爲返回Const**,指向Const *列表的指針。

2

它只是打印一個,因爲您在通過FilterSum獲得有效成本之一後只執行一次PrintCost函數。您需要將FilterCostsBySum功能循環和打印成本推到DynamicVector

編寫一個返回DynamicVector的函數,其中包含滿足所需條件的所有成本。您可以通過更改FilterSum函數來完成此操作,以便不會返回一個Cost,而是將滿足給定條件的任何成本添加到DynamicVector並將其返回。事後重命名函數GetFilteredCosts

最後,在FilterCostsBySum函數中,您將遍歷返回的DynamicVector中的元素並打印成本。

0
if((c->sum)<n) 
{ 
    return c; //if the element(Cost in my case) has the sum<20 return it 
} 

這將立即返回只有10 而是立即返回,加10到列表中。 然後,當您獲得20時,將其添加到列表中。一旦在FilterSum()中循環完成,那麼你可以返回這個列表。