将sum打印为n个数字
Print sum to n numbers
我的问题是…
输入用户号码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;
}
相关文章:
- 比较并显示使用最小值(a,b)和最大值(a、b)升序排列的4个数字
- 为什么随机数生成器不在void函数中随机化数字,而在main函数中随机化
- 检查输入是否不是整数或数字
- 如何(从固定列表中)选择一个数字序列,该序列将与目标数字相加
- 如何用数字处理log(0)
- 最高有效数字侧的第N位
- 如何获取一个数字的前3位
- 查找最接近的大于当前数字的数字的索引
- 找到两对数字,使它们的乘积的绝对差最小化
- 我想做一个彼此不同但重复出现的数字
- 将数字转换为字母(例如:123 转换为一二三)
- C++如何计算用户输入的数字中的偶数位数
- 如何在C++中确定文本文件中的元素是字符还是数字
- 打印数字图案
- C++问题:用户认为数字1-100,程序提出问题不超过6次即可得到答案。无法正确
- 黑客级别的Mini-Max Sum
- 如何检查一个c++字符串中有多少相同的字符/数字
- 求出有多少个数字是完美平方,而sqrt()是L,R范围内的素数
- 将数字打印成文字
- 将sum打印为n个数字