给定数n,求其前面偶数的和

  • 本文关键字:前面 c++
  • 更新时间 :
  • 英文 :


这里给定数字'n',我们已经找到了在它之前的偶数正数的和。为此,我尝试在For循环中放入while循环,但看起来不起作用

#include<iostream>
using namespace std;
int main() {
int n;
cin>>n;
int sum=0;
for(int counter=1;counter<=n;counter++)
while(counter%2==0) {
sum=sum+counter;
}    
cout<<sum<<endl;
return 0;
}

首先,我强烈建议合并某种UI,因为它将帮助您跟踪随着程序复杂性的增长所发生的事情:

cout << "Enter an integer, and I will calculate the sum of all its  preceding, positive integers: ";

你需要交换"while"为了一个"如果"。原因是,你在加和,如果计数器的值是偶数:

for(int counter=1; counter<=n; counter++){
if(counter%2==0){
sum=sum+counter;
}
}

希望有帮助!

您可能需要:

for(int counter=1;counter<=n;counter++)
if(counter%2==0) // this is an if condition, not another loop
{
sum=sum+counter;
}

我们可以在O(1) time complexity中解决这个问题,而不是在数字上迭代。
注意,在数字N之前的偶数之和,形成一个等差数列,其中第一项为2,公差2,项数为⌊N/2⌋

Sum = 2 + 4 + 6 ... N
Sum = 2(1 + 2 + 3 ... N/2)  
Sum = 2((n)*(n+1)/2)   
Sum = n*(n+1) 

其中n =⌊n/2⌋

#include <iostream>
using namespace std; 
int main() {
int N
cin>>N;
N = max(0, N);

long n = N/2;

long sum = n*(n+1);

cout<<sum<<endl;

return 0;
}

最新更新