2

This is a code which multiplies numbers, user enters.

string x;
double t, s = 1;

Console.WriteLine("Enter some numbers: ");
Console.WriteLine("To finish, press Enter");
while ((x = Console.ReadLine()) != "")
{
    t = Convert.ToDouble(x);
    s *= t;
}
Console.WriteLine("The result is: {0}", s);
Console.ReadLine();

It shows the result at the end, but how to make it show a total count of numbers entered? For example: I enter 1, 2 and 3. So total count is 3.

chengbo
  • 5,789
  • 4
  • 27
  • 41

5 Answers5

2
string x;
double t, s = 1;
int count = 0;

Console.WriteLine("Enter some numbers: ");
Console.WriteLine("To finish, press Enter");
while ((x = Console.ReadLine()) != "")
{
    t = Convert.ToDouble(x);
    s *= t;
    count++;
}
Console.WriteLine("The result is: {0}", s);
Console.WriteLine("The count is: {0}", count);
Console.ReadLine();
chengbo
  • 5,789
  • 4
  • 27
  • 41
2
  1. It is good to use TryParse to avoid FormatException
  2. Char.IsDigit returns true is current char is digit (obviously)

Example:

string x;   
double t, s = 1;    
int digitCount = 0;
Console.WriteLine("Enter some numbers: ");
Console.WriteLine("To finish, press Enter");
while ((x = Console.ReadLine()) != "")
{
    if (!Double.TryParse(x, out t))
        continue;
    foreach (var c in x)
        if (Char.IsDigit(c))
            digitCount++;
    s *= t;
}   
Console.WriteLine("The result is: {0}", s);  
Console.WriteLine("The count of digits is: {0}", digitCount);    
Console.ReadLine();
Sharihin
  • 140
  • 11
1

Why not a variable for counter?

    Console.WriteLine("Enter some numbers: ");
    Console.WriteLine("To finish, press Enter");
    int i=0;
    while ((x = Console.ReadLine()) != "")
    {
        i++;
        t = Convert.ToDouble(x);
        s *= t;
    }
    Console.WriteLine("The result is: {0}", s);
    Console.ReadLine();
behtgod
  • 251
  • 3
  • 15
1

You have to count the loop iteration for that use a counter variable:

int loopCounter=0;
while ((x = Console.ReadLine()) != "")
{
    t = Convert.ToDouble(x);
    s *= t;
    loopCounter++;
}
Console.WriteLine("The count is: {0}", loopCounter);
sujith karivelil
  • 28,671
  • 6
  • 55
  • 88
0

You could try counting the number of characters in the string input (x). int temp=x.Length();