Help with rounding INT's

This is a discussion on Help with rounding INT's within the C++ Programming forums, part of the General Programming Boards category; Hi, I have an exam comming up and i noticed something strange in one of the past papers, i wonder ...

  1. #1
    Registered User
    Join Date
    Apr 2008
    Posts
    14

    Help with rounding INT's

    Hi,

    I have an exam comming up and i noticed something strange in one of the past papers, i wonder if anyone could please explain this to me.

    The question is like so..........

    a)The following is a recursive method coded in Java:
    Code:
    int crank(int n){
    if (n==1)
    			return 0;
    else
    		return 1 + crank(n/2);
    }
    iv)Trace the method call crank(12).


    answer is

    ii)n=12, n==1? No, 1+crank(12/2)=1+crank(6)
    n=n=6, n==1? No, 1+[1 + crank(6/2)]= 1+[1+crank(3)]
    n=3,n==1? No, 1+1+[1+crank(3/2)]=1+1+[1+crank(1)]
    n=1, n==1? Yes, 1 + 1 + 1 + 0
    = 3

    i would have though 1.5 would be rounded to 2? is this the same in c++, 3/2 would return an int value of 1?

    Thanks for any help.

  2. #2
    Registered User
    Join Date
    Jan 2005
    Posts
    7,344
    >> 3/2 would return an int value of 1?
    Yes. In integer division (in both C++ and Java) the result is truncated, not rounded. In fact, any non-integer value when converted to an int is truncated, not rounded.

  3. #3
    Registered User
    Join Date
    Apr 2008
    Posts
    14
    Quote Originally Posted by Daved View Post
    >> 3/2 would return an int value of 1?
    Yes. In integer division (in both C++ and Java) the result is truncated, not rounded. In fact, any non-integer value when converted to an int is truncated, not rounded.
    thanks!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. how to handle ints and strings when writing to file
    By agentsmith in forum C Programming
    Replies: 11
    Last Post: 04-23-2008, 05:44 AM
  2. Reading int's from file to array HELP plz
    By GARiMTO in forum C Programming
    Replies: 3
    Last Post: 12-14-2007, 06:12 AM
  3. reading 3 ints from one line, then 3 from another
    By Tokay in forum C++ Programming
    Replies: 10
    Last Post: 11-13-2005, 09:42 PM
  4. Help with rounding a number
    By nickk in forum C Programming
    Replies: 3
    Last Post: 06-02-2004, 12:44 PM
  5. Bitmagic: Sum of 3 ints using a single "+"?
    By Nyda in forum C Programming
    Replies: 10
    Last Post: 04-25-2004, 05:46 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21