Sum the first n numbers

Pages: 12
And why would you want to crash the user's computer?

Does seem a bit drastic. Terminating the current program night be enough of a shock.
And why would you want to crash the user's computer?


Because he didn't followed instructions, so he needs to be punished.
He's lucky we didn't burn his house (yet), the crash was only a warning :P

std::numeric_limits<int>::max() wouldn't work?


yes it works, as well with std::numeric_limits<int>::min()
Last edited on
For the N-1 differences, what am I doing wrong here?

1
2
3
4
5
6
7
for (unsigned i = 0; i < numbers.size(); ++i)
{
	difference = numbers[i] - numbers[i - 1];
	differences.push_back(difference);
	cout << difference << ' ';
}
cout << '\n';


I'm getting an exception thrown. I'm guessing it's because std_lib_facilities.h adds range-checking in the vector's operator[], but I'm not sure where it's being triggered other than that the fact that it's somewhere in the code I've posted here.

And for the check for whether or not the sum is too large to fit into an int, are you saying I should use std::numeric_limits<int>::min() and std::numeric_limits<int>::max() together to check for the range it's in?

Anyway, I'm guessing I don't need that check for exercises 9 and 10 since it's asking to use double instead of int for the numbers now. Unless it'd be good to check for whether the sum is too large fit into a double now, although the book doesn't seem to actually be asking for that.
Your first loop will have i=0, so i-1 will be -1 and below the bottom array bound of numbers[].
You could start from i=1 in this loop; you are after N-1 differences, not N.

If you use numbers.at(i) instead of numbers[i] it should do some automatic bounds checking, although how obvious the out-of-bounds error is I'm afraid that I haven't tried.
Last edited on
As I said, the header file I'm using puts built-in range-checking in operator[]. It treats it as if it were vector::at(). Otherwise it wouldn't be throwing an exception here (which it is).

Edit:

For the program's output, you think this is okay?


Please enter the numbers of values you want to sum: 3
Please enter some integers (press '|' to stop): 12.6 23.5 13.63 24.25 15.9 |
The sum of the first 3 numbers is 49.73
The n-1 differences between adjacent values are:
10.9 -9.87 10.62 -8.35
Last edited on
Topic archived. No new replies allowed.
Pages: 12