打印n个数字

时间:2015-09-05 11:31:04

标签: c++ printing numbers sum

这是我的问题......

从用户输入数字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;

    } 

6 个答案:

答案 0 :(得分: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;
    }
}   

答案 1 :(得分:0)

你需要在你的while循环中加上count + 1。还要添加!= 0触摸你的if语句。

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

答案 2 :(得分:0)

根本不需要使用循环:

总和1..n是

n * (n+1) / 2;

5的倍数之和不高于n

 5 * m * (m+1) / 2

其中m = n/5(整数分割)。结果是

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

答案 3 :(得分:0)

试试这个..

在我的情况下,检查 n 值不等于零和%逻辑

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

答案 4 :(得分:0)

让我们应用一些数学。我们将使用允许我们对算术级数求和的公式。这将使程序更有效,数字更大。

sum = n(a1 + an)/ 2

如果sum是结果,n是inpnum,a1是进展的第一个数字,a是进展中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;
}

答案 5 :(得分:0)

感谢每一个人,但问题解决了。错误非常小。我忘记写&#34;()&#34;如果条件。

#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;

}