两个整数之间能被3整除的所有数之和

方法 1
        try
        {
            Label1.Text = "";
            int c;
            int d;
            int sum = 0;
            if(TextBox1 .Text !=""&&TextBox2.Text !="")
            {
                int a = Convert.ToInt32(TextBox1.Text);
                int b = Convert.ToInt32(TextBox2.Text);
            if (a > b)
            {
                c = b;
                d = a;
            }
            else
            {
                c = a;
                d = b;
            }
            for (int i = c + 1; i < d; i++)
            {
                if (i % 3 == 0)
                {
                    sum = sum + i;
                }
                Label1.Text = " 能被3整除的所有数之和为:" +sum.ToString();
            }
            }
            else if(TextBox1 .Text==""&&TextBox2.Text=="")
            {
                Label1 .Text =" 请输入两个数" ;
            }
            else
            {
                Label1.Text=" 你只输入了一个数" ;
            }
        }
        catch
        {
            Label1.Text = " 输入不正确" ;
        }
方法 2
        int sum = 0;
        if (TextBox1.Text != "" && TextBox2.Text != "")
// 应该先做判断再转换数据类型
        {
             int a = Convert.ToInt32(TextBox1.Text);
             int b = Convert.ToInt32(TextBox2.Text);
 
            if (a > b)
            {
                for (int i = b + 1; i < a; i++)
                {
                    if (i % 3 == 0)
                    {
                        sum = sum + i;
                    }
                }
                Label1.Text = " 能被3整除的所有数之和" + sum.ToString();
            }
            else
            {
                for (int i = a + 1; i < b; i++)
                {
                    if (i % 3 == 0)
                    {
                        sum = sum + i;
                    }
                }
            }
            Label1.Text = " 能被3整除的所有数之和" + sum.ToString();
        }
        else if (TextBox1.Text == "" && TextBox2.Text == "")
        {
            Label1.Text = " 请输入需要计算的两个数字" ;
        }
        else
        {
            Label1.Text = " 你只输入了一个数" ;
        }
 

本文出自 “刘文斌” 博客,谢绝转载!

你可能感兴趣的:(职场,整数,休闲,之和,整除)