C++ C++;对两个整数之间的数字求和的程序
这是我的代码,它在xC++ C++;对两个整数之间的数字求和的程序,c++,C++,这是我的代码,它在xy时就不是了。我怎样才能解决这个问题?我知道问题在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 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;
}
intmain()
{
int x,y;
int-total=0;
cout x;
库蒂;
int计数器=x;
而(计数器如果x>y
,则需要反转x
和y
的角色
if(x > y) {
std::swap(x,y);
}
int counter = x;
//...
一种方法是只添加一个ifx>y
检查,如果逻辑是:
if(x < y) {
int counter = x;
while(counter <= y ){
//...
}
} else if(x > y) {
// roles of x and y are swaped
int counter = y;
while(counter <= x ){
//...
}
} else { // optional
// x = y
// so however you want to handle that, you would do so here
}
除非本练习是关于编写循环的,否则可以使用以下简单公式替换循环:
total = (std::abs(x - y) + 1) * (x + y) / 2;
这是基础数学。这里是使用STL的另一个示例:
int size = std::abs(x - y) + 1;
std::vector<int> v(size);
std::iota(v.begin(), v.end(), std::min(x, y));
int total = std::accumulate(v.begin(), v.end(), 0);
int size=std::abs(x-y)+1;
标准:向量v(大小);
std::iota(v.begin()、v.end()、std::min(x,y));
int total=std::累加(v.begin(),v.end(),0);
Um…if(x
我应该把代码放在哪里?在代码中第一次需要对值重新排序的点之前,但在读入值之后。像这样?int counter=x;if(x>y)std::swap(x,y);while(计数器在笔和纸上用X>Y、X