将sum打印为n个数字

Print sum to n numbers

本文关键字:数字 sum 打印      更新时间:2023-10-16

我的问题是…

输入用户号码n。程序应该输出从1到n的所有数字的和,不包括5的倍数

例如,如果用户输入13,则程序应计算并打印数字的总和:12 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;
    } 

您应该在循环内增加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;
    }
}   

您需要将count+1放入while循环中。还可以在if语句中添加!=0。

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

根本不需要使用循环:

1..n

n * (n+1) / 2;

不大于n的5的倍数之和为

 5 * m * (m+1) / 2

其中m = n/5(整数除法)。因此,结果是

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

试试这个…

在我的条件下,检查n值不等于零和% logic

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

让我们应用一些数学。我们要用一个公式来求等差数列的和。这将使程序在处理更大的数字时更有效率。

sum = n(a1+an)/2

其中sum是结果,n是inpnum, a1是数列的第一个数字,an是在数列中占据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;
}

谢谢大家,但是问题已经解决了。这个错误非常小。我忘了在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;
}