提問者
不知道程式哪裡有問題

問題
-
要做數入一個正整數n,輸出一個最接近n的質數
但程式當輸入n為24.25時卻出現27,但27不是質數,問我應該怎麼打程式碼,作業要交C#的
以下是我打的
private void button1_Click(object sender, EventArgs e)
{
int n = Convert.ToInt32(txt1.Text);
int x = 2;
string msg = n.ToString();
while (x < n)
{
if (n % x == 0)
{
msg = n.ToString();
n++;
continue;
}
else
x++;
}
lblAns.Text = "最接近的質數是" + n;
txt1.Focus();
}
所有回覆
-
你可以解釋一下 你為了解決 "輸入正整數 n,輸出一個最接近 n 的質數"的這段程式碼嗎?
你可以嘗試去自己解讀你的程式碼,你就知道為什麼是 27 了,例如:
input n = 24 , x = 2
n > x 為true (24 > 2 ) 進入迴圈
n % x == 0 為 true (24 被2整除) 所以 msg 被指派了 24,n++ 表示 n 為 25。 continue; 繼續下一圈
input n = 25, x = 2
....以此類推。
你也可以下中斷點 去 trace 你的程式邏輯。
之後你可以按 F11 去一行一行執行 看變數的變化。
-
上面這個會顯示小於n最接近的質數
要改成這樣才會對
int i = 0;
int n = Convert.ToInt32(txt1.Text); ;
bool isPrime = true;
for (int x = n; x> 1; x++)
{
isPrime = true;
for (i = 2; i < x; i++)
{
if (x % i == 0)
{
isPrime = false;
break;
}
}
if (isPrime)
{
MessageBox.Show("最接近的質數是" + i);
break;
}
}- 已編輯 A159014 2018年1月7日 上午 04:28