获取要平方的值,直到大于输入值

时间:2013-12-07 01:16:08

标签: c#

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 Dlicari_loops
{
    public partial class Form5 : Form
    {
        int value;
        int maxvalue;
        public Form5()
        {
            InitializeComponent();
        }

        private void Form5_Load(object sender, EventArgs e)
        {

        }

        private void button1_MouseClick(object sender, MouseEventArgs e)
        {
            value = int.Parse(textBox2.Text);
            maxvalue = int.Parse(textBox1.Text);
            listBox1.Items.Clear();
            while (value < maxvalue)
            {
                try
                {
                    checked
                    {
                        listBox1.Items.Add(value);
                        value = value * value;
                    }
                }
                catch
                {
                    listBox1.Items.Add("You have reached the maximum the computer can do.");
                    break;
                }
            }
            listBox1.Items.Add("You have reached the maximum you had set.");
        }


    }
}

我不确定代码有什么问题,我正在尝试列出一个数字的列表,直到它大于用户放在textBox1中的数字。为了测试我在textBox2中放置2,在textBox1中放置4。

1 个答案:

答案 0 :(得分:0)

您需要在checked块中编写代码才能获得OverflowException

默认情况下,所有的Arthimetic Exceptions都会被忽略。但如果你想提出Arthimetic Overflow Exception,则需要使用checked context

在已检查的上下文中,如果表达式生成的值超出目标类型的范围,则会抛出Arithmetic operation resulted in an overflow

试试这个:

   try
    {
      checked
      {
      listBox1.Items.Add(value);
      value = value * value;
      }
    }
    catch 
    {
     listBox1.Items.Add("You have reached the maximum the computer can do.");
     break;
    }

问题:您尚未使用任何处理程序注册Mouse_Click事件以接收MouseClick事件。

解决方案2:button1.MouseClick += new System.Windows.Forms.MouseEventHandler(this.button1_MouseClick);语句之后在Form5构造函数中添加InitializeComponent();

   public Form5()
    {
        InitializeComponent();
        button1.MouseClick += new System.Windows.Forms.MouseEventHandler(this.button1_MouseClick);
    }