count of digits in large number

General FreeBASIC programming questions.
ganache
Posts: 45
Joined: Aug 04, 2016 9:25

count of digits in large number

Postby ganache » Nov 05, 2019 9:21

here is some code works in c language

Code: Select all

function  countDigit(n As Ulongint) As Integer
return INT(log(10(n)) + 1)
end function
 
Dim As Integer n
input "Enter number: ";n
print countDigit(n)
Sleep

But compiler says expected '' ( " in return statement. No matter how i try to balance the brackets, it still complains.
SARG
Posts: 1157
Joined: May 27, 2005 7:15
Location: FRANCE

Re: count of digits in large number

Postby SARG » Nov 05, 2019 9:44

Hi

Change log(10(n)) by log (n)

Edit : note natural logarithm, divide by log(10) if the need is logarithm of base 10

Code: Select all

function  countDigit(n As Ulongint) As Integer
return INT((log(n)/log(10)) + 1)
end function
 
Dim As Integer n
input "Enter number: ";n
print countDigit(n)
sleep
fxm
Posts: 9980
Joined: Apr 22, 2009 12:46
Location: Paris suburbs, FRANCE

Re: count of digits in large number

Postby fxm » Nov 05, 2019 10:28

But since the Log-based 10 built-in function does not exist in FreeBASIC, the division of Log(n) by Log(10) introduces a rounding error, and therefore the final function may have an error on the number of digit at the borders ( 9-10, 99-100, 999-1000, ...).
Provoni
Posts: 391
Joined: Jan 05, 2014 12:33
Location: Belgium

Re: count of digits in large number

Postby Provoni » Nov 05, 2019 12:04

Code: Select all

print len(str(n))
dodicat
Posts: 6718
Joined: Jan 10, 2006 20:30
Location: Scotland

Re: count of digits in large number

Postby dodicat » Nov 05, 2019 22:45

The crt gives a log10

Code: Select all


#include "crt.bi"
function  countDigit(n As Ulongint) As Integer
return INT(log10(n) + 1)
end function
 
Dim As Integer n
input "Enter number: ";n
print countDigit(n)
Sleep
ganache
Posts: 45
Joined: Aug 04, 2016 9:25

Re: count of digits in large number

Postby ganache » Nov 06, 2019 6:13

thanks guys for the suggestions.
But it seems that the log method is incorrect. Tried it in c.
The code below works for numbers that fit into the largest numeric data type supported
by FB. After that I guess the integers start to overflow...

Code: Select all

Dim As Ulongint number
Dim As Integer count
input "Enter a integer number: ",number
while number > 0
number /= 10
count +=1
wend
print "No. of digits is: ";count
Sleep
End

Return to “General”

Who is online

Users browsing this forum: deltarho[1859] and 8 guests