查找C++中多个 4 的总和

Find summation of multiple 4 in C++

本文关键字:C++ 查找      更新时间:2023-10-16

我有家庭作业来设计一个表单。
我对总和有问题。我不知道他们是什么意思。

单击"总和"按钮时,所有 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;
   }
}