2016-11-08 23 views
-3

こんにちは私はCコードを使用していて、数字が5の倍数で1から5から10までインクリメントされるテーブルを作成しようとしています。ユーザの入力。私が今までに得たことは、1から始まり、1から6、11から16のように5を増やします。それ以上に5を上げることができないところに達するまでユーザの入力。誰かがforループをよりうまくセットアップできるように助けてくれましたか?forループで5をインクリメントする方法

ここで私が話している私のコードのセグメントです:私は入力のn 28として、私は、iは21から16まで1 6から11にインクリメントしてもらう場合は、このコードでそう

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 iは1 5から10まで事前に25

28のおかげでに20から15に増加される28のようにあれば、コードが何をしたいのか26

+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

は、私はあなたと私は= 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; 
     } 
    } 
} 

は、おそらく他の多くのがあります私に印刷文= 1を持つの特別な場合に対処する助けとなる2つのifのステートメントを追加しましたこれを達成するエレガントな方法ですが、これはあなたが試みることのできる簡単な例です。

関連する問題