Results 1 to 2 of 2

Thread: Convert C function to Vb .net [Resolved]

  1. #1

    Thread Starter
    New Member
    Join Date
    Jan 2004
    Posts
    13

    Convert C function to Vb .net [Resolved]

    I tried to covert this but couldnt figure out what i missed
    (I think % is mod????? as i dont know C )

    Code:
    int
    sum(int n)
    {
    	int	ret;
    
    	ret = 0;
    
    	while (n > 0) {
    		ret = ret + (n % 10);
    		n = n / 10;
    	}
    
    	return (ret);
    }
    VB Code:
    1. Public Function sum(ByVal n As Integer) As Integer
    2.  
    3.         Dim ret As Integer = 0
    4.  
    5.         Do While n > 0
    6.             ret = ret + (n Mod 10)
    7.             n = n / 10
    8.         Loop
    9.  
    10.         Return ret
    11.     End Function

    i tested both these functions some times they give the same return value and sometimes they do not...

    If n is 25 they both return 7

    if n is 36 C++ returns 9, vb returns 10


    //////////////////////

    thanx worked great, took me a while to figure out it i got it working properly
    Last edited by James_Carlson; Feb 1st, 2004 at 09:56 PM.

  2. #2
    I wonder how many charact
    Join Date
    Feb 2001
    Location
    Savage, MN, USA
    Posts
    3,704
    On the first iteration: The VB function rounds 3.6 up to 4, whereas the C# function truncates the .6, and makes it 3.

    If you put OPTION STRICT ON, in your VB code at the top, you would see it errors saying a double cannot be converted to an integer. So you must be explicit by using the following code below. VB can only assume you want to round, unless you tell it otherwise.

    I'm not a Math whiz, so I'm not sure which is the correct version (VB vs C). But, you can make your VB function match your C by including math.floor:

    VB Code:
    1. Dim ret As Integer = 0
    2.  
    3.         Do While (n > 0)
    4.             ret = ret + (n Mod 10)
    5.             n = CInt(Math.Floor(n / 10))
    6.            Loop
    7.         Return ret
    Last edited by nemaroller; Feb 1st, 2004 at 10:10 AM.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width