0

我的程序是素数 C# 程序,我需要错误消息来显示当我首先在文本框中添加字母和/或更大的数字时会发生什么。这是我的代码:

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

        private void btcalculate_Click(object sender, EventArgs e)
        {
            // Find all Prime numbers between the first and last prime numbers
            int firstnum = Convert.ToInt32(number1.Text);
            int lastnum = Convert.ToInt32(number2.Text);

            IbPrime.Items.Clear();

            // See which numbers are factors and add them to the list box
            for (int i = firstnum; i <= lastnum; i++)
            {
                if (IsPrime(i))
                {
                    IbPrime.Items.Add(i);
                }

            }
        }
        private bool IsPrime(int num)
        {
            if (num < 2)
                return false;
            // Looks for a number that evenly divides the sum
            for (int i = 2; i <= num / 2; i++)
                if (num % i == 0)
                    return false;

            return true;
        }
    }
}
4

1 回答 1

1

使用int.TryParse.

int firstnum, lastnum;
if (!int.TryParse(number1.Text, out firstnum)){
    // Error
}
if (!int.TryParse(number2.Text, out lastnum)){
    // Error
}
if (firstnum >= lastnum){
    // Error
}
于 2020-06-05T14:04:07.480 回答