2016-11-08 561 views
-3

嗨,我使用C代碼並試圖創建一個表,其中數字以5的倍數從1開始,以5爲單位遞增到10 ...直到一直到用戶的輸入。到目前爲止,我得到的是它從1開始,然後將數字從1增加到6到11到16 ......直到它達到不能再增加5的數量而沒有超過用戶的輸入。有人可以幫助我更好地設置for循環嗎?如何在for循環中將數字增加五位

這是我說的是我的代碼段:

else //run this statement if the user inputs a number greater than 14 
    { 
     printf("Number Approximation1   Approximation2\n-----------------------------------------------------\n"); //prints the header for second table 

     for (i = 1; i <= n; i += 5) 
     { 
      printf("%d  %e   %e\n", i, stirling1(i), stirling2(i)); //calls functions to input approximate factorials 
     } 
    } 

所以用這個代碼,如果我輸入n的28,我得到我從1遞增到6至11至16至21 26.

我想要的代碼做的,如果我輸入n的28是增量i從1到5至10至15至20至25至28

提前感謝什麼!

+0

那麼,你想增加4,5,5,5,5嗎?或者在處理完1之後,你想整理爲下一個5的倍數? –

+0

看起來像在重複性之前和之後有特殊的「一次性」條件。我會特意處理第一個和最後一個案例,並將剩下的部分放在循環中。 – yano

回答

2

試試這個:

{ 
    printf("Number Approximation1   Approximation2\n-----------------------------------------------------\n"); //prints the header for second table 

    printf("%d  %e   %e\n", i, stirling1(1), stirling2(1)); 

    for (i = 5; i <= n; i += 5) 
    { 
     printf("%d  %e   %e\n", i, stirling1(i), stirling2(i)); //calls functions to input approximate factorials 
    } 
} 

這將打印1值,5,10,15,20 ...等

需要注意的是,除了一個額外的代碼行,它的速度更快比在循環內添加一個「if」。

+0

我應該從0開始。 –

+0

在這個問題中,他想從1開始。 –

0

我添加了兩個if聲明這將幫助你處理具有1個在我打印報表=的特殊情況,我= N除了具有打印語句每5

else //run this statement if the user inputs a number greater than 14 
{ 
    printf("Number Approximation1   Approximation2\n-----------------------------------------------------\n"); //prints the header for second table 

    for (i = 1; i <= n; i += 5) 
    { 
     printf("%d  %e   %e\n", i, stirling1(i), stirling2(i)); //calls functions to input approximate factorials 

     if (i == 1){ 
      //when it iterates at the end of this loop, i = 5. 
      //In your example, you will get i from 1 to 5 to 10 up to 25 etc. 
      i = 0; 
     } 

     if ((i + 5) > n){ 
      // for the next loop, it will check if i will exceed n on the next increment. 
      // you do not want this to happen without printing for n = i. 
      //In your case if n = 28, then i will be set to 23, which will then increment to 28. 
      i = n - 5; 
     } 
    } 
} 

可能有其他更優雅的方式來實現這一點,但這只是你可以嘗試的一個簡單例子。