PDA

View Full Version : frustrated


gerald
Nov17-04, 08:50 PM
i'm reading a programming book and one of the problems it asks me to solve is to write a program that determines the larger and smaller values of two integers that the user inputs. I could not use if statements in the program.

I checked the answer and they had used this expression to come solve it.

long larger = (a*(a/b) + b*(b/a))/(a/b + b/a);
long smaller = (b*(a/b) + a*(b/a))/(a/b + b/a);

i was wondering how they have gone about finding those expressions? i'm not a math whiz so i was wondering if there was something in my mathematics education that was lacking.

gerald
Nov17-04, 08:55 PM
sorry for the ambiguous title

matt grime
Nov18-04, 04:32 AM
max(a,b)+min(a,b) = a+b
max(a,b)-min(a,b)= |a-b|


solve for an easier answer

chronon
Nov18-04, 11:40 AM
i'm reading a programming book and one of the problems it asks me to solve is to write a program that determines the larger and smaller values of two integers that the user inputs. I could not use if statements in the program.

I checked the answer and they had used this expression to come solve it.

long larger = (a*(a/b) + b*(b/a))/(a/b + b/a);
long smaller = (b*(a/b) + a*(b/a))/(a/b + b/a);

i was wondering how they have gone about finding those expressions? i'm not a math whiz so i was wondering if there was something in my mathematics education that was lacking.

No there's nothing in your education that is lacking, it's just that writers of programming books have to show how clever they are by inventing silly tricks. This has several problems:

1) When I tried it with negative numbers it didn't work - it may do if you define division using negative integers in a different way, but not with the program I was using.

2) Suppose that you changed your integers to floating point, and your program had this code in. There would be no obvious reason why it needs changing - but suddenly people start finding mysterious errors when running the program.

gerald
Nov18-04, 04:02 PM
hmm, i should have been more specific. it only wanted positive whole numbers and things ive learned in that chapter. this was a very neat trick.

blip
Nov24-04, 05:52 AM
An 'if' statement doesn't take as much computationally (and works with all number), so I'd never use that method if I were you.