• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Ron McLeod
  • Rob Spoor
  • Tim Cooke
  • Junilu Lacar
Sheriffs:
  • Henry Wong
  • Liutauras Vilda
  • Jeanne Boyarsky
Saloon Keepers:
  • Jesse Silverman
  • Tim Holloway
  • Stephan van Hulst
  • Tim Moores
  • Carey Brown
Bartenders:
  • Al Hobbs
  • Mikalai Zaikin
  • Piet Souris

Comparing two functions to determine the max of 4 integers, why one is failing ?

 
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I'm doing this REALLY SIMPLE exercise to determine the max value of 4 integers. I have two functions to compare, one is working but fail in some cases (3/5) and I can't figure out what's wrong. I want to understand what's the difference between these two functions, they look exactly the same but one give the wrong answer. I will give an input example where one of the function fail to return the correct value.

The first function (returning the wrong value)

The second function (works well)

Either I must be tired or just simply dumb that I can't figure out the logic difference between these two function. Any enlightenment ?
 
Marshal
Posts: 22449
121
Eclipse IDE Spring VI Editor Chrome Java Windows
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The first one returns early.
  • If result (whih starts as a) is larger than b, the result (a) is returned, without even checking c or d.
  • Else, if result (which is now b) is larger than c, the result (b) is returned, without even checking d.
  • Else, if result (which is now c) is larger than d, the result (c) is returned. Finally, all variables are checked.


  • The second one updates result without returning in the middle.
  • It starts with a.
  • Then it's the maximum of result (a) and b.
  • Then it's the maximum of result (a max b) and c.
  • Then it's the maximum of result (a max b max c) and d.
  • Then it's returned (a max b max c max d).
  •  
    You showed up just in time for the waffles! And this tiny ad:
    Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop
    https://coderanch.com/wiki/718759/books/Building-World-Backyard-Paul-Wheaton
    reply
      Bookmark Topic Watch Topic
    • New Topic