首页 > 解决方案 > 将两个整数之间的数字相加的 C++ 程序

问题描述

这是我的代码,它在 x < y 时有效。但不是当 x > y 时。我怎样才能解决这个问题?我知道问题出在 while 循环内,我尝试了许多不同的方法,但无法解决问题。

int main()
{
    int x,y;

    int total = 0;
    cout<<"Please give me an integer: ";
    cin >> x;

    cout<<"Please give me another integer: ";
    cin >> y;

    int counter = x;
    while(counter <= y ){

        total += counter;
        ++counter;    
    }

    cout << "The total of the numbers " << total<<endl;      
}

标签: c++

解决方案


除非练习是关于编写循环,否则您可以用这个简单的公式替换循环:

total = (std::abs(x - y) + 1) * (x + y) / 2;

这是基本的算术级数数学。


推荐阅读