Answered by:
Function behavior  Simple Operations
Question

Hi everyone,
I am a VBA rookie, coming from C++.
I am trying to write a simple application to get used to functions and statements in VBA and I get an error which I cannot figure out how it comes from.
This is my console program:
Module Module1 Function square(x As Integer) As Integer Return x = x ^ 2 End Function Function cube(x As Integer) As Integer Return x = x ^ 3 End Function Function sqrt(x As Integer) As Double Return x = Math.Sqrt(x) End Function Sub Main() Dim x, y As Integer Dim z As Double = 0 For i = 0 To 10 x = i ^ 2 y = i ^ 3 z = Math.Sqrt(i) Console.WriteLine("Il numero attuale è: {0}, il suo quadrato è: {1}, il suo cubo è: {2} e la sua radice quadrata è: {3}", i, x, y, z) Next i Console.ReadLine() End Sub End Module
This is the working version but, if instead of this statement:
x = i ^ 2 y = i ^ 3 z = Math.Sqrt(i)
I write this:
x = square(i) y = cube(i) z = sqrt(i)
It returns me values between 0 and 1.
Could you please explain me why?
Thank you
Leo
 Edited by Leonardo U Saturday, March 5, 2016 5:18 PM
Answers

Here is a translation of your code into VBA:
Function square(ByVal x As Double) As Double square = x ^ 2 End Function Function cube(ByVal x As Double) As Double cube = x ^ 3 End Function Function sqrt(ByVal x As Double) As Double sqrt = Math.Sqr(x) End Function Sub Main() Dim x As Double, y As Double, z As Double Dim i As Long For i = 0 To 10 x = square(i) y = cube(i) z = sqrt(i) Debug.Print "Il numero attuale è: " & i & _ ", il suo quadrato è: " & x & _ ", il suo cubo è: " & y & _ " e la sua radice quadrata è: " & z Next i End Sub
Regards, Hans Vogelaar (http://www.eileenslounge.com)
 Marked as answer by Leonardo U Sunday, March 6, 2016 6:42 PM
All replies

Here is a translation of your code into VBA:
Function square(ByVal x As Double) As Double square = x ^ 2 End Function Function cube(ByVal x As Double) As Double cube = x ^ 3 End Function Function sqrt(ByVal x As Double) As Double sqrt = Math.Sqr(x) End Function Sub Main() Dim x As Double, y As Double, z As Double Dim i As Long For i = 0 To 10 x = square(i) y = cube(i) z = sqrt(i) Debug.Print "Il numero attuale è: " & i & _ ", il suo quadrato è: " & x & _ ", il suo cubo è: " & y & _ " e la sua radice quadrata è: " & z Next i End Sub
Regards, Hans Vogelaar (http://www.eileenslounge.com)
 Marked as answer by Leonardo U Sunday, March 6, 2016 6:42 PM
