我想通过一个从LISTBOX到textbox的按钮来显示质数。该接口正确显示质数,但仅显示从1到10的质数,之后算法会更改并将非质数值显示为质数值,如44。
private void primnr()
{
int n = listBox1.Items.Count;
bool prim = true;
for (int i = 2; i < n; i++)
{
for (int j = 2; j <n; j++)
{
if (i!=j && i%j==0)
{
prim = false;
break;
}
}
if (prim)
{
textBox2.Text = textBox2.Text + "Numar prim: " + listBox1.Items[i].ToString() + Environment.NewLine;
}
prim = true;
}
}发布于 2020-04-11 02:21:48
你的算法很好,尽管j不需要超过i的一半。https://dotnetfiddle.net/ZafFsb打印:
2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47,所以我想说你的问题是存储在listBox1.Items[i]中的值,确保Items[43] = 43?附加断点并检查值。
发布于 2020-04-11 03:09:38
让我们将问题一分为二:生成质数(逻辑),并将它们显示给TextBox (UI):
private static IEnumerable<int> Primes() {
yield return 2;
yield return 3;
List<int> primes = new List<int>() {3};
for (int value = 5; ; value += 2) {
int n = (int) (Math.Sqrt(value) + 0.5); // round errors for perfect squares
foreach (int divisor in primes) {
if (divisor > n) {
primes.Add(value);
yield return value;
break;
}
else if (value % divisor == 0)
break;
}
}
}现在,您似乎想要获取具有主索引的列表中的项,即
listBox1.Items[2], listBox1.Items[3], listBox1.Items[5],..., listBox1.Items[101], ...你可以借助Linq查询Primes()。
using System.Linq;
...
var results = Primes()
.Take(index => index < listBox1.Count)
.Select(index => $"Numar prim: {listBox1.Ites[index]}");
// Time to Join results into a single string
textBox2.Text = string.Join(Environment.NewLine, results); https://stackoverflow.com/questions/61145564
复制相似问题