给定两个偶数,求出它们之间所有偶数的平方和

Given two even numbers, find the sum of the squares of all even numbers between them

本文关键字:之间 两个      更新时间:2023-10-16

我的任务是创建一个程序,该程序将提示用户输入两个偶数intsfinputsinput。之后,它应该输出从finputsinput的所有偶数的平方和,包括 和 。

这是我尝试实现此目的的代码:

#include <iostream>
#include <cmath>
using namespace std;
int main()
{
int finput, sinput;
int evens, d;
cout << "Please enter an EVEN number for your first input.(Make sure your first input is less than your second): " << endl;
cin >> finput;
cout << "Please enter an EVEN number for your second input.(Make sure your first input is less than your second): " << endl;
cin >> sinput;
cout << "Results: " << endl << "---------------------------------------------------" << endl;

if (finput % 2 == 0 && sinput % 2 == 0) {
if (finput < sinput) {
while (finput < sinput) {
evens = pow(2, finput);
finput += 2;
}
}
}
else {
cout << "These numbers are not even. try again.";
cout << endl << "Please enter two EVEN numbers. Your first input should be less than your second input (ex. 3  9; 50  100): " << endl;
while (finput % 2 != 0 && sinput % 2 != 0) {
cin >> finput >> sinput;
}
}
}

我相信我必须以某种方式存储循环的每个增量,以便我可以将其添加到运行总计中,但我不知道该怎么做。有人可以告诉我如何完成任务吗?

您可以使用for-loop遍历从finputsinput的所有数字。确保每次递增2以获得从finputsinput的所有偶数。

int sum = 0;
for(int i = finput; i <= sinput; i += 2){
sum += i*i;
}

还有一种O(1)的方法可以得到finputsinput之间所有偶数平方的总和。您可以使用公式1^2 + 2^2 + ... + n^2 = (n)(n+1)(2n+1)/6来实现此目的:

int sum = 4*(sinput/2)*(sinput/2+1)*(sinput+1)/6
- 4*(finput/2)*(finput/2+1)*(finput+1)/6 + finput*finput;

这里有几个问题:

evens = pow(2, finput);

首先,您没有将正方形添加到最终结果中。其次,您正在计算2^finput而不是finput^2。所以这应该是:

evens += pow(finput, 2);

evens += finput * finput;

此外,您需要将累加器初始化为 0:

int evens = 0;