首页 新闻 会员 周边 捐助

如何用C#编写在TextBox1控件中随机输入20个1~1000的整数,单击按钮输出所有素数的和存入TextBox2中

0
[已解决问题] 解决于 2012-06-06 21:20
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 Prime
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            Random r = new Random();
            int []a=new int[20];
            for (int i = 0; i < a.Length; i++)
            {
                if (isprime(a[i])==true)
                {
                   textBox1.Text = r.Next(1, 100).ToString();
                }                
            }
        }
        public static bool isprime( int num)
        {
            bool prime=true;
            int flag = (int)Math .Sqrt (num);
            for (num = 1; num <= 100; num++)
            {
                for (int i = 2; i <= flag; i++)
                {
                    if (num % i == 0)
                    {
                        prime = false;
                        break;
                    }
                }
            }
            return prime;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            int sum = 0;
            
            int[] a = new int[20];
            for (int i = 0; i < a.Length; i++)
            {
                if (isprime(a[i])==true)
                {
                    sum += a[i];
                }
                textBox2.Text =sum.ToString();
            }            
        }
    }
}

这个程序如何修改才能达到

foxing的主页 foxing | 初学一级 | 园豆:5
提问于:2012-06-06 16:31
< >
分享
最佳答案
0

把这一句:

textBox2.Text =sum.ToString();

移到for外面

奖励园豆:5
artwl | 专家六级 |园豆:16736 | 2012-06-06 17:05

还是不行啊!

foxing | 园豆:5 (初学一级) | 2012-06-06 17:15

@itjy:你的代码明显有问题,button1_Click中a中没有值,提供一个DEMO:

public int[] a = new int[20];

public Form1()
{
    InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)
{
    Random r = new Random();
    for (int i = 0; i < a.Length; i++)
    {
        a[i] = r.Next(1, 100);
    }
    textBox1.Text = string.Join(",", a);
}

private static bool isprime(long n)
{
    long b = n / 2;
    if (n < 2) return false;
    if (n == 2) return true;
    else
    {
        if (n % 2 == 0) return false;
        for (long a = 3; a <= b; a = a + 2)
        {
            if (n % a == 0) return false;
            b = n / a;
        }
        return true;
    }
}

private void button1_Click(object sender, EventArgs e)
{
    int sum = 0;
    for (int i = 0; i < a.Length; i++)
    {
        if (isprime(a[i]) == true)
        {
            sum += a[i];
        }
    }  
    textBox2.Text = sum.ToString();
}
artwl | 园豆:16736 (专家六级) | 2012-06-06 17:30

@artwl: Very good

foxing | 园豆:5 (初学一级) | 2012-06-06 18:38
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册