2017-03-10 4 views
-1

입력 한 숫자까지 모든 소수를 출력하려고하는데 왜 작동하지 않는지 알 수 없습니다.내 코드에 어떤 문제가 있습니까? C++

누군가 내가 뭘 잘못했는지 설명해 줄 수 있습니까?

if (a%b == 0) 
{ 
    prime = true; 
     break; 
} 

당신은 이런 식으로 작성해야합니다 :

:

if (a%b == 0) 
{ 
    prime = false; 
     break; 
} 

또한 bool prime = false; 마침내

bool prime = true;이 코드 변경이 코드에서

#include<iostream> 
#include<string> 
using namespace std; 
int main() 
{ 
    int number; 

    cout << "Enter Number: "; 
    cin >> number; 

    for (int a = 2;a <= number;a++) 
    { 

     bool prime = false; 

     for (int b = 2;b < a;b++) 
     { 
      if (a%b == 0) 
      { 
       prime = true; 
       break; 
      } 

      if (prime = true) 
       cout << a << endl; 
     }  
    } 

    system("pause"); 
    return 0; 
} 
+2

의 몇 명백한 포인트 : 1) 소수는 * 1을 제외하고 어떤 숫자로 나눌 수없고 2)'='는 대입입니다. 비교를 원한다면 대신'=='를 원한다. –

답변

1

0
if (prime == true) 
    cout << a << endl; 

for loop

외부이어야 코드는 더 나은 같은 것입니다 :

#include<iostream> 
#include<string> 
using namespace std; 
int main() 
{ 
    int number; 

    cout << "Enter Number: "; 
    cin >> number; 

    for (int a = 2; a <= number; a++) 
    { 

     bool prime = true; 

     for (int b = 2; b < a; b++) 
     { 
      if (a%b == 0) 
      { 
       prime = false; 
       break; 
      } 
     } 

     if (prime == true) 
      cout << a << endl; 
    } 

    system("pause"); 
    return 0; 
} 

결과 (예) :

enter image description here

0
for(i=2;i<=number;i++) 
{ 
     ct=0; 
     for(j=2;j<i;j++) 
     { 
      if(i%j==0) 
       { 
         ct=1; 
         break; 
       } 
     } 
     if(ct==0) 
     { 
      printf("%d \t",i); 
     } 
} 
관련 문제