- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我的任务是创建一个程序,该程序将提示用户输入两个偶数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;
关于c++ - 给定两个偶数,求出它们之间所有偶数的平方和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62825770/
尝试构造一段代码,返回range(1, limit)中的一个数是否为两个平方数之和(平方数如1**2 = 1,2**2 = 4 - 所以我试图分配给一个数字列表,它们是否是任何这些平方数的总和组合 -
我确实有一个矩阵,行中包含观察值(不同 pH 下的测量值),数据点作为列(随时间变化的浓度)。因此,一行包含一个 pH 值的不同数据点。 我确实想对数据拟合 ODE。所以我定义了一个成本函数,并想计算
令我惊讶的是,调用 np.inner 计算平方和比在预先计算的平方数组上调用 np.sum 快大约 5 倍: 对这种行为有什么见解吗?实际上,我对平方和的快速实现很感兴趣,因此也欢迎提出这些想法。 最
我使用lm(x~y1 + y1 + ... + yn)估计了线性回归模型,并为了应对当前的异方差性,我让 R 估计了稳健的标准误差 coeftest(model, vcov = vcovHC(mode
我使用lm(x~y1 + y1 + ... + yn)估计了线性回归模型,并为了应对当前的异方差性,我让 R 估计了稳健的标准误差 coeftest(model, vcov = vcovHC(mode
我是一名优秀的程序员,十分优秀!