我需要创建一个程序,显示用户输入的两个数字之间的偶数和的整数之和。
这是我到目前为止所做的,它不起作用!?
请指出我正确的方向!
//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;
答案 0 :(得分:2)
尝试完成您的计算机在进行循环时正在执行的操作。在纸上做。跟踪num2,num1及其值。 你会很快看到问题所在。
答案 1 :(得分:0)
尝试循环
for(; num1<=num2;num1++)
{
if(num1%2==0)
sum=sum+num1
}
答案 2 :(得分:0)
for (num2 = num1; num1 <= num2; num1 += 2) sum += num1;
你已经覆盖了你的停止点。 :)
我还建议更有意义的名字:
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;
/* ... */