给定两个偶数,求出它们之间所有偶数的平方和
Given two even numbers, find the sum of the squares of all even numbers between them
我的任务是创建一个程序,该程序将提示用户输入两个偶数ints
,finput
和sinput
。之后,它应该输出从finput
到sinput
的所有偶数的平方和,包括 和 。
这是我尝试实现此目的的代码:
#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
遍历从finput
到sinput
的所有数字。确保每次递增2
以获得从finput
到sinput
的所有偶数。
int sum = 0;
for(int i = finput; i <= sinput; i += 2){
sum += i*i;
}
还有一种O(1)
的方法可以得到finput
和sinput
之间所有偶数平方的总和。您可以使用公式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;
相关文章:
- 给定两个偶数,求出它们之间所有偶数的平方和
- C++需要帮助从用户那里获得一个整数,并确保它在另外两个整数之间
- 如何在两个 boost::multi_arrays (C++) 之间执行数学运算?
- 查找字符在两个索引之间出现的次数
- 如何使用 OpenCV 解码在两个 UWP 应用之间发送的图像字节?
- C++两个源文件之间共享的枚举的静态实例
- 如何使用发送数据包所花费的时间计算两个节点之间的距离?
- 以天C++为单位的两个时间戳之间的差异
- 将向量之间的数字放在另一个向量之间<vector>>如果两个数字的差值为 1
- 我已经建立了递归关系,它找到了两个字符串之间最长的连续公共字符串,我怎么能跳过其中一个字符串中的一个字符
- 通过插槽和信号在不同线程中的两个qt对象之间进行通信
- 在C++中查找两个向量之间最相似的值
- 两个有符号数字之间的距离
- Directx 12 :在两个进程之间共享图形内存
- 如何找到两个日期之间的时间差异(以秒和纳秒为单位)?
- 是否有一种标准方法来计算两个 asctime() 值之间的天数
- 如何找到两个棋盘平面之间的角度?
- 计算两个迭代器之间的距离时"Vector Iterators Incompatible"
- 使用 Dijkstra 算法跟踪两个节点之间的最短路径
- 无法理解代码背后的逻辑,这是在两个给定数字之间生成素数的优化问题