PDA

View Full Version : Something about Visual Basic.


peter1988
Sep 28, 2009, 05:55 AM
May anyone tell me how to do this calculation,the code into Visual Basic?
(Question)
If the user inputs 15 and 3, the first number is a multiple of the second. If the user inputs 2 and 4, the first number is not a multiple of the second.

Perito
Sep 28, 2009, 11:21 AM
I'm not sure I understand the question.

Is this the question? How can I determine if the second number is an integral multiple of the first? If that is the question, this is how to do it (This is a VB6 program)

Dim FirstValue As Double
Dim SecondValue As Double

FirstValue = 15
SecondValue = 3

If (CInt(FirstValue / SecondValue) * SecondValue = FirstValue) Then
Call MsgBox("The second value is an integral multiple of the first", vbInformation)
Else
Call MsgBox("The second value is NOT an integral multiple of the first", vbInformation)
End If

You can also do it this way (using the "\" operator, the integral division operator).

If ((FirstValue \ SecondValue) * SecondValue = FirstValue) Then
Call MsgBox("The second value is an integral multiple of the first", vbInformation)
Else
Call MsgBox("The second value is NOT an integral multiple of the first", vbInformation)
End If

The key is the "CInt" or the integer division operator "\". Other languages have other functions to do the same thing (Trunc, Fix, IFIX, etc. VB has the FIX operator.) Basically, you throw away the fractional part (or the remainder). If you then multiply by the divisor, you should get back the original number. If you don't, it's not an integral multiple.

Note that VB is somewhat more forgiving than some other languages. In some languages. Round-off errors can make the IF statement fail incorrectly. In these cases, you would have to do something like this:

Dim TestValue as double
TestValue = ((FirestValue \ SecondValue) * SecondValue) - FirstValue

if ABS(TestValue) < 0.0000001 then
' The second value is an integral divisor
else
' The second value is NOT an integral divisor
end if

steadysimple
Mar 28, 2010, 08:03 PM
How about this one:

Dim the first as Integer
Dim theSecond as Integer
dim theThird as Integer
dim theFourth as Integer

the first = 15
thesecond = 3
if the first > theSecond then
theThird = thesecond * 2
theFourth = the first
else
theThird = the first * 2
theFourth = theSecond
end if

if theThird = theFourth then
msgbox "it's multiple"
else
msgbox "it's not multiple"
end if

costas0811
Mar 29, 2010, 06:10 PM
I think what you are looking for is the mod function

If firstNumber Mod secondNumber = 0 Then
MsgBox "Is a multiple"
Else
Msgbox "Is NOT a multiple"
End If

The mod function will divide the two numbers and return only the remainder, if the remainder is 0 then the second number is a multiple of the first one.