2015-09-05 112 views
-2

這是我的問題...打印總數到n號

從用戶輸入數字n。該程序應輸出從1到n的所有數字的總和,不包括5的倍數。

例如,如果用戶輸入13,則程序應該計算並打印數之和:1 2 3 4 6 7 8 9 11 12 13(注意5,10不包括在總和)

我做了下面的程序,但它不工作.. 任何一個可以幫助我預先感謝您...

#include <iostream> 
    using namespace std; 
    int main() 
    { 
     int inputnumber = 0; 
     int sum = 0; 
     int count= 1; 
     cout<<"Enter the number to print the SUM : "; 
     cin>>inputnumber; 

     while(count<=inputnumber) 
     { 
      if (count % 5!=0) 
      { 
       sum = sum + count; 
      } 

     } count = count +1; 
     cout<<"the sum of the numbers are : "<<sum; 

    } 
+0

我不承認錯誤「不工作」。 – stark

回答

0

你應該增加count內循環,而不是外面:

while(count<=inputnumber) 
{ 
    if (count % 5!=0) 
    { 
     sum = sum + count; 
    } 
    count = count +1; // here 
} 

請注意,順便說一句,使用for循環在這裏會更方便。此外,sum = sum + count可能短於sum += count

for (int count = 1; count <= inputnumber; ++count) 
{ 
    if (count % 5 != 0) 
    { 
     sum += count; 
    } 
} 
0

您需要將count + 1放入while循環中。也加上!= 0 tou你的if語句。

while(count<=inputnumber) 
     { 
      if (count % 5!=0) 
      { 
       sum = sum + count; 
      } 
     count = count +1; 
     } 
0

無需使用一個循環在所有:

總和1..n的是

n * (n+1)/2; 

的5不高於n中的倍數的總和是

5 * m * (m+1)/2 

其中m = n/5(整數devision)。因此

n * (n+1)/2 - 5 * m * (m+1)/2 
0

試試這個..

在我的病情結果是,檢查ñ值不等於零%的邏輯

int sum = 0; 
int n = 16; 
for(int i=0 ; i < n ;i++) { 
    if(i%5 != 0){ 
     sum += i; 
    } 
} 
System.out.println(sum); 
0

讓我們運用一些數學。我們將使用一個公式來讓我們總結一個算術級數。這將使程序的方式更高效的數字更大。

總和= N(A1 +的)/ 2

凡總和的結果,n是inpnum,a1爲進展的第一數目和一個是ocuppies N(該地方inpnum)。

因此,我所做的是計算所有數字從1到inpnum的總和,然後將5的所有倍數之和從5減去n。

#include <iostream> 

using namespace std; 

int main (void) 
{ 
    int inpnum, quotient, sum; 

    cout << "Enter the number to print the SUM : "; 
    cin >> inpnum; 

    // Finds the amount of multiples of 5 from 5 to n 
    quotient = inpnum/5; 

      // Sum from 1 to n  // Sum from 5 to n of multiples of 5 
    sum = (inpnum*(1+inpnum))/2 - (quotient*(5+(quotient)*5))/2; 
    cout << "The sum of the numbers is: " << sum; 
} 
0

感謝每一位,但問題就解決了。這個錯誤非常小。我忘了在if條件下寫「()」。

#include <iostream> 
using namespace std; 
int main() 
{ 
    int inputnumber = 0; 
    int sum = 0; 
    int count= 1; 
    cout<<"Enter the number to print the SUM : "; 
    cin>>inputnumber; 

    while(count<=inputnumber) 
    { 
     if ((count % 5)!=0)//here the().. 
     { 
      sum = sum + count; 
     } 
     count = count +1; 
    } 
    cout<<"the sum of the numbers are : "<<sum; 

}