有关在Windows窗体应用程序中检查素数的问题

时间:2014-10-14 04:13:51

标签: c# primes

我的应用是测试素数。我第一次输入素数时,结果为true,并向用户显示数字。但第二次,prime number check没有按预期运行。这是我的代码:

private void button1_Click(object sender, EventArgs e)
{
    label3.Text = textBox1.Text;

    float a = (float)Convert.ToDouble(textBox1.Text);

    if (check_Number(ref a) == true)
    {
        ResultCheck.Text = "Input Number is Prime";
    }
    else if (check_Number(ref a) == false)
    {
        ResultCheck.Text = "Input Number is not Prime";
    }
} 

1 个答案:

答案 0 :(得分:1)

这是一个使用试验分区的示例程序。

enter image description here

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 PrimeCheck
{
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        label1.Text = textBox1.Text; 

        double testthis = 0;
        if (double.TryParse(textBox1.Text, out testthis))
        {
            if (CheckForPrime(testthis))
            {
                MessageBox.Show("prime time!!");
            }
        }
    }

    bool CheckForPrime(double number)
    {//there are better ways but this is cheap and easy for an example

        bool result = true;//assume we are prime until we can prove otherwise

        for (double d = 2; d < number; d++)
        {
            if (number % d == 0) 
            {
                result = false;
                break;
            }
        }

        return result;
    }
}
}