0

我有作业要设计一个表格。
我对总和有疑问。我不知道他们是什么意思。

当点击“求和”按钮时,将查找所有大于 100 和小于 200 的 4 的倍数之和,并在结果编辑框中显示结果。

我的回答是这样的:

if(num>100)||(num<200)

  sum=sum+num
4

2 回答 2

7

From what I can gather, it's asking you to "find" all numbers that are divisible by 4, that are between 100 and 200, and then sum them together. I'll provide the pseudo code, but as it's homework, you'll need to figure this one out on your own. :)

// 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

To help you get started with the code, you'll want to use the for loop, e.g.

for (var index = 0; i < 10; i++)
{
    // do something 10 times
}

and you'll also want to use the Mod operand to determine if the current number if divisible by 4. e.g.

if (number % 2 == 0)
{
    // number is even
}
else
{
    // number is odd
}

Alternative approach

As suggested by @benhoyt, you could increment your loop index by 4 each time, that way you wouldn't need to x % y on each iteration, and your number of overall loop executions would go down. Here's the pseudo code:

// 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

Although this approach requires 2 loops, the number of overall loop executions will be reduced. Within the 2nd loop we're adding 4 to the index, thus we won't need to check if x % y is true. Our 2nd loop, instead of being a for loop, will now look like this:

// 2nd loop
while (index < 200)
{
    // add index to array
    index += 4
}
于 2012-04-24T13:27:38.543 回答
-2

//我需要恢复我之前给出的断章取义的答案。

int i = 100, sum = 0;
while (i <200)
{
   i = i +4;
   if ( i % 4 == 0)
   {
      sum += i;
   }
}
于 2012-04-24T14:51:16.413 回答