C++ Programming help

后端 未结 5 456
甜味超标
甜味超标 2021-01-29 06:38

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

5条回答
  •  走了就别回头了
    2021-01-29 07:29

    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;
    

提交回复
热议问题