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();


    }
   }
 }
4

3 に答える 3

2

変更する必要があります

int total;

int total = 0;

この理由は、あなたがもっとよく見るとしたら

total += num;

次のように書くこともできます

total = total + num;

この合計は、最初の使用に対して割り当てられていません。

于 2012-07-27T04:04:20.180 に答える
0

totalに初期値を割り当てないでください。おそらく、次のものが必要です。

int total = 0;
于 2012-07-27T04:04:35.573 に答える
0

他の答えは正しいですが、変数は1回しか割り当てられないため、変数を初期化する必要のない代替FWIWを提供します。:)

var total = textBox1.Text
    .Split(',')
    .Select(n => Convert.ToInt32(n))
    .Sum();
于 2012-07-27T06:58:54.103 に答える