count of digits in large number

General FreeBASIC programming questions.
Post Reply
ganache
Posts: 47
Joined: Aug 04, 2016 9:25

count of digits in large number

Post by ganache »

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: 1766
Joined: May 27, 2005 7:15
Location: FRANCE

Re: count of digits in large number

Post by SARG »

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
Moderator
Posts: 12110
Joined: Apr 22, 2009 12:46
Location: Paris suburbs, FRANCE

Re: count of digits in large number

Post by fxm »

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: 514
Joined: Jan 05, 2014 12:33
Location: Belgium

Re: count of digits in large number

Post by Provoni »

Code: Select all

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

Re: count of digits in large number

Post by dodicat »

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: 47
Joined: Aug 04, 2016 9:25

Re: count of digits in large number

Post by ganache »

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
Post Reply