查找C++中多个 4 的总和
Find summation of multiple 4 in C++
我有家庭作业来设计一个表单。
我对总和有问题。我不知道他们是什么意思。
单击"总和"按钮时,所有 4 的倍数的总和更大将找到大于 100 和小于 200,结果将显示在结果中编辑框。
我的回答是这样的:
if(num>100)||(num<200)
sum=sum+num
据我所知,它要求您"找到"所有可被 4 整除的数字,介于 100 和 200 之间,然后将它们相加。我将提供伪代码,但由于这是家庭作业,您需要自己弄清楚这一点。:)
// Create an array of integers
// Loop from 100 to 200
// If current index is divisible by 4
// Add to array
// Sum the array of integers
为了帮助您开始使用代码,您需要使用 for
循环,例如
for (var index = 0; i < 10; i++)
{
// do something 10 times
}
您还需要使用 Mod 操作数来确定当前数字是否可以被 4 整除。
if (number % 2 == 0)
{
// number is even
}
else
{
// number is odd
}
替代方法
正如 @benhoyt 所建议的,您可以每次将循环索引增加 4,这样您就不需要在每次迭代时x % y
,并且您的整体循环执行次数会下降。下面是伪代码:
// Create an array of integers
// Set index to 100
// (This loop determines where we should start)
// Whilst index is not divisible by 4, and index is less than 200
// Add 1 to index
// Whilst index is less than 200
// Add index to array
// Add 4 to index
// Sum the array of integers
尽管此方法需要 2 个循环,但总体循环执行次数将减少。在第二个循环中,我们将 4 添加到索引中,因此我们不需要检查 x % y
是否为真。我们的第二个循环,而不是一个for
循环,现在看起来像这样:
// 2nd loop
while (index < 200)
{
// add index to array
index += 4
}
//我需要对我给厄勒的断章取义的答案进行补偿。
int i = 100, sum = 0;
while (i <200)
{
i = i +4;
if ( i % 4 == 0)
{
sum += i;
}
}
相关文章:
- 正在查找文档以获得PS4平台的C++中的设备信息
- 在C++中查找文件
- 模板元程序查找相似的连续类型名称
- 在UNIX系统中使用DIR查找文件的字节大小
- 查找最接近的大于当前数字的数字的索引
- 有没有一种方法可以创建一个带有哈希表的数据库,该哈希表具有恒定时间查找功能
- 查找后更改类变量
- 使用正则表达式regex_search在字符串中查找字符串
- 使用gcc从静态链接的文件中查找可选符号
- 在C++中查找范围的长度
- 算法问题:查找从堆栈中弹出的所有序列
- 在Windows中查找扬声器输出的当前音量级别
- 如何在C++中使用X509证书模在令牌中查找私钥
- 使用.find函数在c++中查找字符和另一个字符之间的大小
- 在 Windows 上,是否可以让 dll 在不使用 PATH 环境变量的情况下在另一个文件夹中查找依赖项?
- 在 for 循环中查找问题时遇到困难
- 如何在文件中查找字节序列
- 试图创建一个多线程程序来查找0-100000000之间的总素数
- 使用堆查找第K个最大元素的时间复杂性
- 一个函数,用于查找字符串1包含字符串2 c++的次数