- 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. For example: “Please enter the number of values you want to sum:” 3 “Please enter some integers (press '|' to stop):” 12 23 13 24 15 | “The sum of the first 3 numbers ( 12 23 13 ) is 48.” Handle all inputs. For example, make sure to give an error message if the user asks for a sum of more numbers than there are in the vector.
- Modify the program from exercise 8 to write out an error if the result cannot be represented as an int.
So in exercise 9 it says to write out an error message if the result cannot be represented as an int, but if I'm only adding up integers here the only thing I can think of here that would cause a number to not be able to be represented as an int would be if there's some integer overflow and the integer goes above INT_MAX or below INT_MIN but how exactly can I detect this?
This is my code:
#include<vector>
#include<cmath>
#include<string>
#include<iostream>
#include<algorithm>
#include<stdexcept>
using namespace std;
int main()
{
int N = 0;
vector<int> values;
cout << "Please enter the number of values you want to sum." << '\n';
cin >> N;
cout << "Please enter some numbers" << '\n';
for (int tempnum; cin >> tempnum; )
{
values.push_back(tempnum);
}
if (N > values.size())
{
cout << "How am I gonna add up more numbers than you gave me?" << '\n';
}
else
{
int total = 0;
for (int i = 0; i < N; i )
{
total = values[i];
}
}
}
But I can't just check if total is above or below INT_MAX or INT_MIN because INT_MAX 1 or something returns some random negative value so I'm not really sure how to do this
CodePudding user response:
You can do this with some arithmetic:
So you want to know if acc x > INT_MAX
, where acc
is the accumulator (the sum so far) and x
is the next element. Adding them together may overflow though. But acc > INT_MAX - x
is equivalent and x is already stored in an int
. So this can also not underflow, bc. x
can be at most INT_MAX
.
I.e., just transform the inequation to avoid overflow. In this case, subtract x from both sides.
That only works for positive x though, thanks to user interjay for pointing this out.
With negative x, this becomes a subtraction:
acc (-x) > INT_MAX
acc - x > INT_MAX
This can not overflow, because we are subtracting from acc
. But it may underflow, so the question becomes:
acc - x < INT_MIN
acc < INT_MIN x
So:
int acc = 0;
for (int i = 0; i < N; i) {
int x = values[i];
if (x >= 0 && acc > (INT_MAX - x)) {
cout << "ERROR: Overflow.";
return 1;
} else if (x < 0 && acc < (INT_MIN - x)) {
cout << "ERROR: Underflow.";
return 1;
} else {
acc = x;
}
}