如何将数组中的所有元素相乘? [英] How to multiply all elements from array?
问题描述
我开始学习C#,并且正在编写一个程序,该程序将首先要求用户输入数字列表.当用户完成输入输入后,我想对用户在输入中提供的每个数字取平方.用户输入的示例是 2 3 5
.
I am beginning to learn C# and am writing a program that will first ask a user to enter a list of numbers. When the user finishes entering the input, I would like to square every number the user provided in the input. An example of user input is 2 3 5
.
这是代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Program
{
class Third
{
public static void Main()
{
Console.WriteLine("Enter how much numbers");
int howMuch = int.Parse(Console.ReadLine());
int[] num = new int[howMuch];
int sum = 0;
for (int i = 0; i < num.Length; i++ )
{
sum = num[i] * num[i]; // this is what i did but it does not work?
}
Console.WriteLine(sum);
Console.ReadLine();
}
}
}
具体地说,我首先希望在 numbers
数组中捕获用户输入.然后,我想对创建的 num
数组中的每个数字求平方.我的程序怎么了?
Specifically, I would first like the user input to be captured in the numbers
array. And then I would like to square each number in the num
array that was created. What's wrong with my program?
推荐答案
这可能会更好一些,尽管还有很多工作要做!
This might be a LITTLE better, although there is still quite a bit of tidying up to do!
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Program
{
class Third
{
public static void Main()
{
Console.WriteLine("Enter how many numbers");
int howMuch = int.Parse(Console.ReadLine());
int[] num = new int[howMuch];
int sum = 1;
for(int i=0;i<num.Length;i++) //allows you to fill the array
{
Console.WriteLine("Please enter an integer");
sum *= int.Parse(Console.ReadLine()); // this will now multiply the value to sum, as your comment suggests
}
Console.WriteLine(sum);
Console.ReadLine();
}
}
}
编辑
sum *= num[i];
应该做你想做的事!
这篇关于如何将数组中的所有元素相乘?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!