C ++ While循环问题

时间:2017-10-21 08:58:15

标签: c++ while-loop

我在如何设置while和do / while循环时遇到了一些问题。

例如,我有一个问题,在输入中我有2个int数字(让他们称之为a,b),我需要计算一个总和。总和是特殊的:a +(b)+(b - 1)+(b - 2)+ ... + 0.而cicle是必须的。但我不知道如何设置它。我试过了,但我不知道它是否正确。有人能让我知道吗?

这里有我的代码

#include <iostream>
#include <stdlib.h>

using namespace std;

int main(int argc, char *argv[])
{
 // Variables
 int a,b;
 int sum;

 cout<<"Insert a:";
 cin>>a;
 cout<<"Insert b:";
 cin>>b;

 // Show a,b
 cout<<"variables:"<<" "<<a<<" e "<<b<<endl;

// Condition: a>0 & b>0
while(a>0 && b>0)
{
 sum=a+b;
 b--;  
} cout<<"Sum:"<<sum;
system("PAUSE");    
return 0;
}

例如,如果我输入a = 5且b = 9,则总和为6.是不是?

2 个答案:

答案 0 :(得分:2)

您可能会想到重写while部分。我建议你只检查b条件。因为,您只更改b值。请参阅以下代码 -

sum = a; // as you want to add a only once, you should add a to sum before the loop
while(b)
{
 sum += b;
 b--;  
}

如果您有任何疑惑,请随时询问。

答案 1 :(得分:0)

在进入sum = a;循环之前,您必须设置while并在每次迭代中将其更新为sum += b;。希望这些能解决您的问题。