|
-
Feb 1st, 2004, 03:21 AM
#1
Thread Starter
New Member
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:
Public Function sum(ByVal n As Integer) As Integer
Dim ret As Integer = 0
Do While n > 0
ret = ret + (n Mod 10)
n = n / 10
Loop
Return ret
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.
-
Feb 1st, 2004, 09:45 AM
#2
I wonder how many charact
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:
Dim ret As Integer = 0
Do While (n > 0)
ret = ret + (n Mod 10)
n = CInt(Math.Floor(n / 10))
Loop
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
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|