Нужно понимать, как добавлять значения в цикле - PullRequest
0 голосов
/ 19 октября 2018
#include <iostream>
using namespace std;

int main()
{
    int numint, sum, a, b, ctr;
    cout << "Enter the number of intervals: ";
    cin >> numint;
    ctr = 0;
    while (ctr != numint) 
    {
        cout << "Enter the lower and upper bounds of the interval: ";
        cin >> a;
        cin >> b;
        ctr++;
    }
    cout << "The sum of the " << numint << " intervals is: [" << a << "," << b << "]";
    return 0;
}

Мне нужно добавить верхние границы интервала (а) и нижние границы интервала (б).Это зависит от количества интервалов.

Ответы [ 3 ]

0 голосов
/ 19 октября 2018

Что касается того, что я понял из вопроса, сначала вам нужно int resultA=0, а другое для b, и продолжайте добавлять в цикле:

#include <iostream>

using namespace std;

int main()
{
int numint,sum,a,b,ctr;

int result = 0;
int resultA=0;
int resultB=0;
cout << "Enter the number of intervals: ";
cin >> numint;
ctr=0;
while (ctr!=numint)
{
    cout << "Enter the lower and upper bounds of the interval: ";
    cin >> a;
    cin >> b;
    resultA+=a;
    resultB+=b;
    ctr++;
   }
    result = resultA + resultB ;
    cout << "The sum of the " << numint << " is: " <<  result;


return 0;
}
0 голосов
/ 19 октября 2018

Я думаю, это то, что вы ищете:

#include <iostream>
using namespace std;

int main() {
    int numberOfIntervals;
    int lowerBound;
    int upperBound;
    int counter;

    int lowerBoundSum = 0;
    int upperBoundSum = 0;

    cout << "Enter the number of intervals: ";
    cin >> numberOfIntervals;
    counter = 0;
    while (counter != numberOfIntervals) {
        cout << "Enter the lower and upper bounds of interval " 
             << counter << ": ";
        cin >> lowerBound;
        cin >> upperBound;
        lowerBoundSum += lowerBound;
        upperBoundSum += upperBound;
        counter++;
    }
    cout << "The sum of the lower bounds is " << lowerBoundSum 
         << endl;
    cout << "The sum of the upper bounds is " << upperBoundSum 
         << endl;


    return 0;
}
0 голосов
/ 19 октября 2018

здесь:

cout << "The sum of the " << numint << " intervals is: [" << a << "," << b << ]";

вы не добавляете значения, а просто печатаете их

вместо этого используете некоторую переменную аккумулятора и выполняете математические операции перед ее печатью, например:

int main()
{
int numint,sum,a,b,ctr;

int result = 0;

cout << "Enter the number of intervals: ";
cin >> numint;
ctr=0;
while (ctr!=numint)
{
    cout << "Enter the lower and upper bounds of the interval: ";
    cin >> a;
    cin >> b;
    ctr++;
   }
    result = a + b ;
    cout << "The sum of the " << numint << " is: " <<  result;


return 0;
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...