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(); } } } }
这个程序如何修改才能达到
把这一句:
textBox2.Text =sum.ToString();
移到for外面
还是不行啊!
@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: Very good