2016-11-08 559 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; 
     } 
    } 
} 

可能有其他更优雅的方式来实现这一点,但这只是你可以尝试的一个简单例子。