Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Incorrect sum when adding up numbers

Ok, here's the code to add indefinite numbers and present the sum in c++. But error is that addition taking place is of first number and the last digits of all the other numbers. For example if i want to add 30 + 40 + 55 + 70, my program counts 30 + 0 + 0 + 5 + 0 = 35. What am I doing wrong?

#include <iostream>

using namespace std;

int main()
{
    int num = 0;
    int sum = 0;

    cout << "Please enter numbers you want to add and end with N or n: ";

    for (;;)
    {
        cin >> num;
        sum += num;
        cout << endl;

        char indicator ('q');

        cin >> indicator;
        if (( indicator == 'n') || (indicator == 'N'))
            break;

    }
    cout << "The sum is: " << sum << " ";

    return 0;
}
like image 413
Adeel Malik Avatar asked Dec 21 '25 02:12

Adeel Malik


1 Answers

I'm not sure I fully understand what you are trying to do, but if you want to add a list of integers terminated by an N (or n) character, then you should read each entity as a string, see if it's the terminating character, and if it's not, then convert it to an integer:

int sum = 0;

while (true) {
    std::string s;
    std::cin >> s;

    if (tolower(s[0]) == 'n')
        break;

    sum += std::stoi(s);
}

Of course, the above code is only a skeleton -- in production code, you should always check if I/O operations succeeded and sanitize your input. A more complete example would be:

std::string s;
while (std::cin >> s) {
    int ch = s[0];

    if (ch > 0 && tolower(ch) == 'n')
        break;

    try {
        sum += std::stoi(s);
    } catch (const std::invalid_argument &e) {
        // handle conversion error
        break;
    } catch (const std::out_of_range &e) {
        // handle out-of-range error
        break;
    }
}
like image 159
The Paramagnetic Croissant Avatar answered Dec 22 '25 16:12

The Paramagnetic Croissant



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!