gpt4 book ai didi

c++ - 求和未确定范围内的奇数和偶数

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

我的任务是创建一个程序,用户可以在其中输入起始值和结束值。然后程序应该对该范围内的所有数字求和。此外,它应该对奇数和偶数求和。我的问题是确定用户范围内的哪些数字是奇数,哪些是偶数,然后对这些值求和。总和循环有效,但我已经尝试了多个其他循环来计算奇数和偶数的总和,但都没有成功。因此,如果有人可以帮助我根据偶数或奇数对这些数字求和。

#include <iostream>
using namespace std;
int main()
{

int sum = 0, start, endnumber;
int sumall = 0, c=0;
cout << "Please enter the starting integer\n";
cin >> start;
cout << "Please enter the ending integer\n";
cin >> endnumber;
while (endnumber <= start)
{
cout << "Please enter the starting integer\n";
cin >> start;
cout << "Please enter the ending integer\n";
cin >> endnumber;
}

while (start <= endnumber)
{

sumall = sumall + start;
++start;

}
std::cout << "The sum is: " << sumall << std::endl;

return 0;
}

最佳答案

您需要用模数检查范围内的每个数字。例如:

if( start%2 == 0 )  // even
{
evenSum+=start;
}
else // Odd
{
oddSum+=start;
}

这样就可以了。

关于c++ - 求和未确定范围内的奇数和偶数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21663562/

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