给定一个用数字初始化的数组,如何在不使用 LINQ 或 foreach
的情况下添加它的所有元素?
我的不完整代码如下:
namespace WindowsApplication5
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public void Form1_Load(object sender, EventArgs e)
{
method1(sum1);
MessageBox.Show("The Sum Is = " + sum1.ToString(), "Addition",MessageBoxButtons.OK,MessageB…
}
int sum1;
int[] str = new int[4] { 1, 2, 3, 4 }; // i want to add this 4 values and to be printed on a messagebox//
public int method1(int str)
{
sum1 = str;
return sum1;
}
}
}
输出显示“总和为 0”,而不是 10。
谢谢。
附注:我不想使用 LINQ 或 foreach
。
最佳答案
首先,您有不好的全局变量。如您所述,不使用 LINQ
或 Foreach
,请尝试类似的操作:
//Doesn't have to be a button click...just an example.
private void button1_Click(object sender, EventArgs e)
{
int[] values = new int[4] { 1, 2, 3, 4 };
int result = Sum(values);
MessageBox.Show(result.ToString());
}
int Sum(int[] values)
{
int sum= 0;
for (int i = 0; i < values.Length; ++i)
{
sum += values[i];
}
return sum;
}
关于c# - 数组总和中的 Windows 应用程序问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5722539/