0

Hello all,

I am working through Beginning Microsoft Visual C# 2008 I was asked to create a console application that multiplies 4 input values. I decided to take all 4 values at once and multiply them. Here is my code:

            string inputNumbers;
            string userName;
            Console.WriteLine("Enter your name:");
            userName = Console.ReadLine();
            Console.WriteLine("Welcome {0}!", userName);
            Console.WriteLine("Now give me 4 numbers seperated by a space:");
            inputNumbers = Console.ReadLine();
            string[] numbers = inputNumbers.Split(' ');


            Console.WriteLine("The product of {0} * {1} * {2} * {3} is {4}.", 
                numbers[0], 
                numbers[1], 
                numbers[2], 
                numbers[3], 
                Convert.ToDouble(numbers[0]) * Convert.ToDouble(numbers[1]) * Convert.ToDouble(numbers[2]) * Convert.ToDouble(numbers[3])
                );

Is there an easier way to do the converts in a loop somehow, or an easier way in general of achieving the same result?

Edited by pritaeas: Moved to C#

4
Contributors
4
Replies
28
Views
3 Years
Discussion Span
Last Post by castajiz_2
1

It's C# so this is the best place for it.

This is the only way I can think to do it using a loop...

double Total = Convert.ToDouble(numbers[0]);

for (int i = 1; i < numbers.Count(); i++)
{
    Total = Total * Convert.ToDouble(numbers[i]);
}

It would be the best way if you have a lot of numbers or the amount of numbers would change but if you only have a constant amount of about 4 or less number the way you have done it is good.

Edited by ChrisHunter

0

I'd go with a loop as well. You could do it using more advanced methods, but since this exercise is at the beginner level, it's better to keep things simple.

0

You could use the

ConsoleKeyInfo

class and the

ConsoleKey

struct. Put them in a do while loop and you should be able to manage your code with spaces after the number input. Don't forget to combine them with the Console.Read() or .ReadLine() methods...

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.