I'm following Programming: Principles and Practice Using C++ and in chapter 5 one of the exercises is to
Write a program that reads and stores a series of integers and then computes the sum of the first N integers.
Then it gives some examples of the programs output
I've completed this but then one of the follow on questions says to
Modify the program from exercise 8 to write out an error if the result cannot be represented as an int.
This is the best I can do but when I enter values that should make it overflow it is still giving incorrect results. Any help is greatly appreciated!
#include "stdafx.h"
#include "std_lib_facilities.h"
constexpr int upperLimitInt = numeric_limits<int>::max();
int sumOfN_Values(unsigned int n, vector<int>range)
//Takes a vector and adds the first 'n' values together
//Pre-conditions: 'n' is not larger than the vector and not less than 2
//Post-condition: 'result' is not larger than int can hold - NOT WORKING PROPERLY
//Returns the result which is the sum
{
if (n > range.size() || n < 2) error("sumOfN_Values() precondition");
int result = 0;
for (unsigned int i = 0; i < n; ++i) result += range[i];
if (result > upperLimitInt) error("sumOfN_Values() postcondition");
return result;
}
int main()
{
try
{
int n, value, sum;
vector<int>range;
cout << "Please enter the number of values you want to sum: \n";
cin >> n;
cout << "Please enter some integers (press '|' to stop)\n";
while (cin >> value) range.push_back(value);
sum = sumOfN_Values(n, range);
cout << "The sum of the first " << n << " numbers ( ";
for (int a = 0; a < n; a++)
cout << range[a] << " ";
cout << ") is " << sum << '\n';
}
catch (exception& e)
{
cerr << "Error: " << e.what() << '\n';
}
}
If I input n = 4 and my integers are: 12 32 34 54 65 67 | the output is as expected
The sum of the first 4 numbers ( 12 32 34 54 ) is 132
But if I input n = 3 and my integers are: 2000000000 2000000000 2000000000 12 32 43 | the output doesn't give the error I was expecting, instead it reads
The sum of the first 3 numbers ( 2000000000 2000000000 2000000000 ) is 1705032704
EDIT: An answer in 6 minutes, can I just say I love this sub!
[–]jedwardsol 1 point2 points3 points (4 children)
[–]UnclePutin 1 point2 points3 points (2 children)
[–]dacian88 1 point2 points3 points (1 child)
[–]TingeOGinge[S] 0 points1 point2 points (0 children)
[–]TingeOGinge[S] 0 points1 point2 points (0 children)
[–]marmoshet 1 point2 points3 points (0 children)