2015-10-17 87 views
1

這個C++代碼打印出以下素數的素數的位置:3 5 7.查找基於用戶輸入

int main() 
{ 
for (int a=2; a<10; a++) 
    for (int b=2; b<a; b++) 
    { 
     if (a % b == 0) 
      break; 
     else if (a == b+1) 
      std::cout << a << " "; 

    } 
return 0; 
} 

我的問題是怎麼想的程序來顯示其質數的位置?

例子:

Enter a number : 2  
The 2th prime number is : 5 

Enter a number : 3  
The 3th prime number is : 7 
+0

我想你找到答案。所以你可以接受我的回答並投票給我 –

回答

0

對於這一點,你可以在array像做店質數:

int main() 
{ 
int array[10]; 
int counter = 0; 
for (int a=2; a<10; a++) 
    for (int b=2; b<a; b++) 
    { 
     if (a % b == 0) 
      break; 
     else if (a == b+1) 
     { 
      array[counter] = a; 
      counter ++; 
     } 
    } 
for (int i=0; i<2; i++) 
{ 
cout<<"Enter a number : "; 
int position; 
cin>> position; 
cout<< "The "<<position<<"th prime number is "<< array[position-1]<<endl; 
} 
return 0; 
} 

輸出:

Enter a number : 2  
The 2th prime number is : 5 

Enter a number : 3  
The 3th prime number is : 7