C++ Programming help
You create a program that displays the sum of even integers between and including two numbers entered by the user ..
ex) 2 and 7 = the sum of 12 (2+4+6)
this is what i have so far! butt if u can just put me in the right direction that would be helpful
//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;
if ( num1 > num2)
{
cout << "Invalid entry. Final number must be less than the first number. Please try again." << endl;
}
for ( int sum = (((num1 + 1)/2)*2); num1 <= (((n开发者_运维百科um2 + 1)/2)*2) ; sum = 2 + (((num1 + 1)/2)*2) )
return 0;
} //end of main function
In your for loop it should be like this.
double sum = 0.0;
for(i = num1; i <= num2; i++){
if(i % 2 == 0){ // Is our number even
sum += i;
}
}
That's it and it print out sum.
I would simplify your for loop
for(int i = num1; i <= num2; i++) {
if(i % 2 == 0) sum += i;
}
This will look at twice as many numbers, but honestly that's not all that much more expensive.
You could also do it in O(1) time by taking advantage of the fact that the sum 1..n == n*(n+1)
Here's a very simple example in Java, translating it to C++ won't be too difficult I hope :) no C++ compiler on this machine :-X
import java.util.*;
class DoubleSum {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int num1 = sc.nextInt();
int num2 = sc.nextInt();
int low = (num1 - 1)/ 2;
int high = num2 / 2;
int sumLow = (low*(low + 1));
int sumHigh = (high*(high + 1));
int sum = sumHigh - sumLow;
System.out.println(sum);
}
}
You are using the same variable to control the for loop and to the sum, this won't work. Try this:
int even1 = num1 % 2 == 0 ? num1 : num1+1;
int even2 = num2 % 2 == 0 ? num2 : num2-1;
for (int i = even1; i <= even2; i += 2) sum += i;
Note that you don't really need a for loop:
int even1 = num1 % 2 == 0 ? num1 : num1+1;
int even2 = num2 % 2 == 0 ? num2 : num2-1;
// how many numbers you will sum (remember they are even, so we need to divide by 2)
int count = 1 + (even2 - even1)/2;
sum = (even1 + even2) * (count/2);
if (count % 2 == 1) sum += (even1 + even2)/2;
for(int i = num1; i <= num2; i++)
{
if(!(i & 1))
sum += i;
}
Your code would end up in an infinite loop.
Look at the for() loop. You have the condition
num1 <= (((num2 + 1)/2)*2)
to determine whether your loop terminates. However, since num1 itself is never incremented, and num1 < num2 is guaranteed, this condition will always be true - which means your for loop would never end. I would also suggest using a separate looping variable.
精彩评论