开发者

Sum of even integers problem

开发者 https://www.devze.com 2023-02-19 10:33 出处:网络
I need to create a program that displays the开发者_StackOverflow社区 sum of the even integers between and including two numbers entered by the user.

I need to create a program that displays the开发者_StackOverflow社区 sum of the even integers between and including two numbers entered by the user.

This is what I have so far and it's not working!?

So point me in the right direction please!

//Advanced30.cpp - displays the sum of the even integers between and 
//including two numbers entered by the user
//Created/revised by <your name> on <current date>

#

    include <iostream>
    using namespace std;

    int main()
    {
        // declare variables
        int num1 = 0;
        int num2 = 0;
        int sum= 0;

        cout << "Enter the First Number:" << endl;  
        cin >> num1;     
        cout << "Enter the Second Number:" << endl;    
        cin >> num2;      


        for (num2 = num1; num1 <= num2; num1 += 2) sum += num1;       
        num1 = num1 % 2 == 0 ? num1 : num1+1; 
        num2 = num2 % 2 == 0 ? num2 : num2-1;

        return 0;


Try to do EXACTLY what your computer is doing when it's doing the loop. Do it on a paper. Keep track of num2, num1 and their value. You'll see very quickly where the problem is.


try the Loop

for(; num1<=num2;num1++)
{
if(num1%2==0)
 sum=sum+num1
}


    for (num2 = num1; num1 <= num2; num1 += 2) sum += num1;

You've overwritten your stop-point. :)

I would also suggest more meaningful names:

int start=0;
int real_start=0;
int stop=0;
int sum=0;

/* ... */

real_start = (start % 2) ? start+1 : start;

for (int i = real_start; i <= stop; i+=2) sum += i;

/* ... */
0

精彩评论

暂无评论...
验证码 换一张
取 消