[問題] 判定質數問題

看板C_and_CPP作者 (暴君)時間16年前 (2009/10/16 21:20), 編輯推噓2(201)
留言3則, 3人參與, 最新討論串1/1
小弟最近剛接觸c語言 自學到判定質數的部分 書上寫的程式碼為 # incldue <stdio.h> # include <stdlib.h> # include <string.h> # include <math.h> int main(int argc, char *argv[]) { int n, max, i; char ans[80]; scanf("%d", &n); max = (int)sqrt(n); strcpy(ans,"這是質數!\n"); for(i = 2; i < max, i++) { if(n % 2 == 0) { strcpy(ans,"這不是質數!\n"); break; } } system("pause"); return 0; } 可是不知道為什麼在 scanf("%d",&n); 就被揪出錯誤 所以我自己寫了另一個改一下 # include <stdio.h> # include <stdlib.h> # include <math.h> int main(int argc, char *argv[]) { int n, max, i; scanf("%d", &n); max=(int)sqrt(n); for(i = 2;i <= max; i++) { if(n % i == 0) { printf("這不是質數!\n"); break; } else { printf("這是質數!\n"); break; } } system("pause"); return 0; } 這次可以正常執行 只是在因數裡有3的時候就還是會被判定成質數(ex: 15 21) 想請問板上前輩這是為什麼 -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 58.114.185.8

10/16 21:25, , 1F
你只檢查是不是 2 的倍數而已....||||||
10/16 21:25, 1F

10/16 21:29, , 2F
else裡的break
10/16 21:29, 2F

10/16 21:43, , 3F
明白了!謝謝各位!
10/16 21:43, 3F
文章代碼(AID): #1As7Cu8T (C_and_CPP)