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

问题描述 投票:-3回答:1

我的应用程序是测试素数。我第一次输入素数时,结果是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";
    }
} 
c# primes
1个回答
1
投票

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

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;
    }
}
}
© www.soinside.com 2019 - 2024. All rights reserved.