gpt4 book ai didi

c++ - 在 C++ 中查找多个 4 的总和

转载 作者:太空宇宙 更新时间:2023-11-04 16:27:43 25 4
gpt4 key购买 nike

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

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

我的回答是这样的:

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

sum=sum+num

最佳答案

据我所知,它要求您“找出”100 到 200 之间的所有可被 4 整除的数字,然后将它们相加。我将提供伪代码,但由于这是家庭作业,您需要自己解决这个问题。 :)

// 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 operand确定当前数字是否可以被 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
}

关于c++ - 在 C++ 中查找多个 4 的总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10298705/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com