2012-07-27 61 views
0

我正在製作一個程序,在文本框中添加用逗號(,)分隔的列表編號。 例如:1,12,5,23 在我的總數+ = num;我一直使用總共未使用的本地變量;獲取未分配的變量錯誤的使用

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Linq; 
using System.Text; 
using System.Windows.Forms; 

namespace WindowsFormsApplication1 
{ 
public partial class Form1 : Form 
{ 
    public Form1() 
    { 
     InitializeComponent(); 
    } 

    private void button1_Click(object sender, EventArgs e) 
    { 
     string str = textBox1.Text; 
     char[] delim = { ',' }; 
     int total; 
     int num; 
     string[] tokens = str.Split(delim); 

     foreach (string s in tokens) 
     { 

      num = Convert.ToInt32(s); 
      total += num; 

     } 
     totallabel.Text = total.ToString(); 


    } 
    } 
} 

回答

2

您需要更改

int total; 

int total = 0; 

這樣做的原因是,如果你看一下

total += num; 

接近它也可以是寫爲

total = total + num; 

其中第一次使用的總數未分配。

+0

我不敢相信我錯過了,謝謝。這就是爲什麼當我疲倦的時候我不這樣做。 – 2012-07-27 14:07:02

0

你不分配一個初始值合計,也許你需要:

int total = 0; 
0

其他的答案是正確的,但我會提供一個替代FWIW不需要初始化變量,因爲它是隻分配一次。 :)

var total = textBox1.Text 
    .Split(',') 
    .Select(n => Convert.ToInt32(n)) 
    .Sum(); 
相關問題