Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
485 views
in Technique[技术] by (71.8m points)

c# - How to multiply all values in an array?

I have an assignment where I need to find the product of all of the numbers in an array, I'm not sure how to do this.

    int[] numbers = new int[SIZE];

    Console.WriteLine("Type in 10 numbers");
    Console.WriteLine("To stop, type in 0");
    for (int input = 0; input < SIZE; input++)
    {
        userInput = Console.ReadLine();
        numberInputed = int.Parse(userInput);

        if (numberInputed == ZERO)
        {
            numberInputed = ONE;
            break;
        }
        else
        {
            numbers[input] = numberInputed;
        }

    }

This is where I'm trying to find the product of all of the numbers in the array.

    foreach (int value in numbers)
    {
        prod *= value;
    }

    Console.WriteLine("The product of the values you entered is {0}", prod);

What am I doing wrong in the foreach statement? Thanks in advance

Edit, left out my declared values

    const int SIZE = 10;
    const int ZERO = 0;
    string userInput;
    int numberInputed;
    int prod = 1;

It now works when I type in all ten values but if I put a 0 in order to break the loop then everything equals 0. How do I prevent a 0 from being entered into the array?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It's possible you initialize prod to 0, which means no matter what numbers are in your array, prod will remain 0. Make sure you initialize it to 1 to get the correct result:

int prod = 1;
foreach (int value in numbers)
{
    prod *= value;
}

You could also use Linq's Aggregate extension method to do the same thing:

using System.Linq; // put with other using directives

int prod = numbers.Aggregate(1, (a, b) => a * b);

Update

The real problem (which I failed to notice before) is that your array isn't being fully populated if you break out of your loop early. So any array entries you didn't set are still initialized to 0. To fix this, use a List<int> instead of an int[]:

using System.Collections.Generic; // put with other using directives

List<int> numbers = new List<int>(SIZE); // Capacity == SIZE

...

for (int input = 0; input < SIZE; input++)
{
    ...
    if (numberInputed == ZERO)
    {
        break;
    }
    else
    {
        numbers.Add(numberInputed);
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...