2014-09-05 48 views
-5

我有以下問題,其中X = 10,Y = 85和D = 30已經定義。在C編程中返回值

int solution (int X, int Y, int D) 
{  
     //put your code here 
} 

我需要計數的數目,直到X的值達到爲Y,當X被添加到d中,例如X = X + d

我知道返回值必須是3,這是我所做的,

int count = 0; 
    int solution (int X, int Y, int D) 
    { 
     if (X<=Y) 
     { 
      count++; 
      X = X+D; 
     } 
     else 
     { 
     return count; 
     } 
    } 

但我只是一個返回值爲0,我在哪裏做錯了?

+2

你忘了循環? – 2014-09-05 10:15:33

+6

if語句不返回任何東西 – 2014-09-05 10:16:33

+1

因爲它不會返回其他部分,它將返回默認返回值0.但它肯定給出了「不是所有控制路徑都返回值」的錯誤/警告? – Arpit 2014-09-05 10:19:21

回答

0

如果我明白你想要什麼,並且數字是否定的。

解決方案:

int solution (int X, int Y, int D) 
    { 
     int count = 0; 

     while (X < Y) 
     { 
      count++; 
      X += D; 
     } 

     return count; 
    } 

count真的沒有是全球性的,因爲你的方法將返回它。

1

你不應該使用if .. else來做到這一點。因爲它只會執行一次。當功能執行完成後它不會返回任何東西,if沒有return聲明!

您應該使用循環對做 -

int count = 0; 
int solution (int X, int Y, int D) 
{ 
    while(X<=Y) // executes till the condition fails 
    { 
     count++; 
     X = X+D; 
    } 
} 

在您有count爲全局變量這種情況下。所以不需要返回它。但如果你把它作爲一個地方一個,你應該回到它 -

int solution (int X, int Y, int D) 
{ 
    int count = 0; 
    while(X<=Y) // executes till the condition fails 
    { 
     count++; 
     X = X+D; 
    } 
    return count; 
} 
+0

如果將它作爲全局變量返回count變量,那麼它有什麼用處? – 2014-09-05 13:19:19

0
int solution (int X, int Y, int D){ 
    int count; 
    for(count = 0; X <= Y; X += D) 
     ++count; 
    return count; 
} 
3

您應該使用部門來解決這個問題:

if (X > Y) 
    return 0; 

int count = (Y - X)/D + 1; 
return count;