My homework was to make a function that added two integers. The function was to throw an exception if the sum of the two integers were larger than INT_MAX. I got it working perfectly. Ive tried many test cases with much success. Now I just want to maybe make it more concise I guess. I just feel like I have excess if statements. Here is my function
Since you are using just ints, you could sort of cheat and do this:
1 2 3
longint total = a +b; //a long int can store much bigger numbers than a normal int
if(total > INT_MAX) throw("Sum larger than INT_MAX");
return (int)total;
int add(constint& a, constint& b)throw(char*)
{
int total;
if(b <= (INT_MAX - a))
{
total = a + b;
}
elsethrow("Sum larger than MAX_INT");
return total;
}
because you want that
a+b <= MAX
Substracting a on boith sides:
b <= MAX - a
If this case is not matching, the sum between a and b is larger than MAX and you can throw the exception
herbert I see what you are saying. I tried that test case so I had to add the if b<0 code in line 19. Because if b is negative and we are only working with ints that means that a can be at the greatest INT_MAX, so go ahead and add the two numbers if and only if b is negative.
Thanks all for the Input.
Firedraco that is super smart. I dont know if my teacher would like that though. I think we were supposed to only use ints but im not sure. I see exactly how yours would work though.
Here is the actual assignment though if you guys were interested.
Your new job as a Computational Physicist involves calculations using very large integers. However, some of the results are incorrect. For example, when adding very large positive integers, sometimes the results become a negative number. After consulting with a Computer Science professor (for a large fee :) ), you have determined in some cases the results are too large to fit into an integer. Write a function that adds two integers and returns the results. If the result is too large to fit into INT_MAX, throw an error message. Test the function in the main using a try and catch.
I just tryed your code. At first I was thinking this way and I ran into problems. It seems to work sometimes but not for all cases. For example using your code. If you entered
add(-100,-100) it would throw an exception
alslo if you added
add(INT_MAX,-5) it would throw an exception
both of the above cases should work. Because -100 + (-100) is -200 and that should fit into INT_MAX
and INT_MAX + (-5) should fit because it is simply INT_MAX - 5 < INT_MAX
I think your code works if you are not using negative numbers.
Thats why I had to pick off each case in my code because it is a harder problem than it seems.