#! /usr/bin/perl -w # # sigfigs.pl - Compute the significant digits in a number. # # Created by Neil J. Gunther, Tue Jun 4 22:55:41 2002 # Read the number in from the keyboard. print "Enter a number: "; $numstring = ; chomp($numstring); # Toss the carriage return $skipzero = ''; $i = 0; if ($numstring =~ /\./) { # Check for presence of decimal point. ($int, $frac) = split(/\./, $numstring); # Separate integer and fractional parts $digstring = $int . $frac; # Concatenate sans decimal point $numfigs = length($digstring); while ($i < $numfigs ) { # Find position of first non-zero digit # Compare FORWARDS from LEFTmost digit... if ($digstring =~ /^$skipzero(\d)/) { $sigfigs = $numfigs - $i; last if ($1 ne '0'); } $skipzero = $skipzero . '.'; $i++; } } else { # No decimal point, so just scan the integer... $numfigs = length($numstring); while ($i < $numfigs) { # Find position of first non-zero digit # Compare BACKWARDS from RIGHTmost digit... if ($numstring =~ /(\d)$skipzero$/) { $sigfigs = $numfigs - $i; last if ($1 ne '0'); } $skipzero = $skipzero . '.'; $i++; } } # Print out the result. print "The number '$numstring' contains $sigfigs significant digits.\n";