一个C#窗体应用,大一的,我不会

创建一个 Windows 窗体应用程序,计算1+1/2+1/4+1/7+1/11+1/16+1/22 +...,当第i 项的值<10-4时结束,计算累加结果 Sum 和总项数 n,并只列示出公式中的前 10 项文本(以…结束)。

img

👀👀

using System;
using System.Windows.Forms;

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

        private void button1_Click(object sender, EventArgs e)
        {
            // 定义变量
            double sum = 0;   // 存储总和
            int n = 0;        // 存储项数
            double eps = 0.0001;  // 定义需要达到的精度
            double a = 1;     // 定义初始值

            // 存储前10项的文本
            string formula = "";

            // 使用for循环计算和
            for (int i = 1; i <= 10; i++)
            {
                n++; // 每次循环项数加1
                sum += a;  // 将当前项的值加入总和中
                formula += "1/" + (n + (n - 1)) + " + "; // 保存当前项的文本

                // 计算下一项
                a = 1.0 / (n + (n - 1));

                // 判断当前项是否小于给定精度
                if (a < eps)
                {
                    // 如果小于精度,退出循环
                    break;
                }
            }

            // 将最后一项的加号替换成省略号,用于表示截断的项
            formula = formula.Substring(0, formula.Length - 3) + "...";

            // 使用MessageBox显示结果
            MessageBox.Show("The sum of the series is " + sum + "\n" +
                "The total number of terms is " + n + "\n" +
                "The first 10 terms are: " + formula);
        }
    }
}