Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Isn't the sum of a series of integers always an integer? (Stroustrup PPP - Chapter 5, Question 9)

Tags:

c++

Question 9:

Modify the program from exercise 8 to write out an error if the result cannot be represented as an int.

To give more context to question 9, here's Question 8:

Write a program that reads and stores a series of integers and then computes the sum of the first N integers. First ask for N, then read the values into a vector, then calculate the sum of the first N values.

So my question is:

If I have a vector of integers, and I sum the elements in the vector, won't my result always be an integer? If so, what is question 9 in Stroustrup PPP asking for?

*if it helps, here's a link to my code for question 8.

like image 685
lardandweed Avatar asked Nov 17 '25 16:11

lardandweed


2 Answers

Yes, the result will always be an integer, but it may not be the "correct" solution because there was an overflow.

For instance if your integer type can only represent from -3 to 4, and you sum 2 and 3, what's the correct result? 5, but your integer result could be -3 instead (assuming 2-complement signed integers). That's what you need to detect.

Just an indication for the solution. numeric_limits<T>::max() is the max you can represent. If your current sum is sum and the new value value, what can you say about max - value and sum with regard to the overflow?

like image 158
Matthieu Brucher Avatar answered Nov 19 '25 08:11

Matthieu Brucher


Indeed mathematically speaking the set of integers is closed under addition.

But the int of C++ is bound by numeric_limits<int>::min() and numeric_limits<int>::max(). The behaviour on exceeding this range is undefined.

like image 40
Bathsheba Avatar answered Nov 19 '25 07:11

Bathsheba



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!