I want to print the the product of digits in a number using the following code. Plz view the following code and find me the error in it and help me to solve it in 2 different ways using static method and also in general manner using do while loop in the main method
namespace Prime2
{
class ProdOfDigits
{
public static double evalulate(double no)
{
if (no == 0) return 0;
double temp = 1;
do
{
temp = (no % 10) * temp;
no = no / 10;
} while (no > 0);
return temp;
}
static void Main(string[] args)
{
double num,rem,temp=1;
Console.WriteLine("Enter the Number to find the Product of Digits ");
num = double.Parse(Console.ReadLine());
/* do
{
// rem = num % 10;
//temp = rem * temp;
temp = (num % 10) * temp;
num = num / 10;
} while (num>0);*/
/*if (rem==0)
Console.WriteLine("Product of Digits in Number is Zero");*/
Console.WriteLine("Product of Digits in Number is {0}", ProdOfDigits.evalulate(num));
}
}
}
VulpesPosted Jun 6, 2014, 7:40 PM
This is because there may be digits both before and after the decimal point.
Worse still, since doubles do not have an exact representation in the machine, dividing by ten may actual change the digits. For example, instead of 3 you might get 2.9999998879.
It's therefore best to convert the double to a string and extract the digits from that: