small math question int+int = error

Blitz3D Forums/Blitz3D Beginners Area/small math question int+int = error

The forum is locked. These are the original blitzbasic.com forums, kept so they can still be read. No new topics, replies or edits can be made here. To join in, head over to the Blitz3D+ forums.

Hey man, whipped up a function for this. It's not as efficient as it could be, but, it works, that's whats important. Your only limit on digits, is the length of a string, which is...er....very long? :o)

; Add large number example
; By Ross C

Graphics 800,600


Global first_number$
Global second_number$

first_number = Input(" Enter the first number: ")
second_number = Input(" Enter the second number: ")

DebugLog(" first string = "+first_number)

Print " Equals:" + AddLarge$(first_number,second_number)


WaitKey()
End


Function AddLarge$(n1$,n2$)

	Local answer$ = ""
	Local temp_string$ = ""
	Local holder$ = ""
	Local temp_total% = 0
	Local a1%
	Local a2%
	Local carry% = 0
	Local templarge$
	Local tempsmall$

	If Len(n1) => Len(n2) Then ; get which number has the largest length
		templarge = n1 ; then set it to "templarge" for the longest string and "tempsmall" for the smallest one
		tempsmall = n2
	Else
		templarge = n2
		tempsmall = n1
	End If
	
	For loop = 0 To Len(templarge)-1; set up a loop which will loop through all the characters of the longest string "templarge"
		
		a1 = Mid$( templarge,Len(templarge)-loop,1) ; set a INT "a1" to the digit of the longest loop
		If Len(tempsmall) > loop Then ; if the smallest string is long enough, then set INT "a2" to the "loop" digit from the right
			a2 = Mid$( tempsmall,Len(tempsmall)-loop,1)
		Else
			a2 = 0 ; else just make it zero to fit the calculation
		End If
		
		temp_total = a1 + a2 + carry ; perform the calculation, taking into account the carry from a prevoius loops calculation
		If a1 + a2 > 9 Then
			carry = 1 ; set the carry to 1 if the calculation for the two digits is greater than 9 (the highest single digit)
		Else
			carry = 0 ; else set it to zero
		End If
		
		If loop > 0 Then ; make sure the loop is greater than 0 before putting the contents of the temp_string into the holder string
			holder = temp_string ; used to hold the contents of the temp_string. Basically so you can insert a digit at the beginning
								 ; of the temp_string variable. Copy to holder, set temp_string to the digit, then add the holder string back on :o)
		End If

		temp_string = Str(Right$(temp_total, 1)) ; set the temp_string to the rightmost digit in temp_total. This eliminates adidng calculation that went over 9
		temp_string = temp_string+holder ; add the holder string back on, to make up the answer so far
		answer = temp_string ; make the answer string equal temp string so far. Could get away with just using temp_string, but i didn't think of that :o)
		
	Next

	Return answer$ ; return the answer back across
	
End Function