题目描述
创建一个C#Windows应用程序,输入n,求1+2+3+..+n。
操作步骤
1>首先在Windows窗体中添加2个Label控件,1个TextBox,和1个Button控件。各控件的主要属性设置如下表。
控件 | 属性 | 属性设置 | 控件 | 属性 | 属性设置 |
label1 | Text | n: | textBox1 | Name | txtNum |
label2 | Text | "" | button | Name | btnOk |
Name | lbShow | Text | 确定 |
2>在窗体设计区中双击“btnOk”按钮,系统自动为按钮添加“Click”事件及对应的事件方法,然后在源代码视图中编辑代码。
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 Test3_5 { public partial class Test3_5 : Form { public Test3_5() { InitializeComponent(); } private void btnOk_Click(object sender, EventArgs e) { int n = Convert.ToInt32(txtNum.Text); int i = 1; int sum=0; while(i<=n){ sum+=i; i++; } lblShow.Text = "1+2+3+....+n = " + sum; } } }