//Testing numbers for primality
#include <iostream>
#include <cmath>
using namespace std;
int main() {
int n; //User input number
int i; //Input number will be divided by i
int count;
count = 0;
cout << endl;
while(n != 'q') {
cout << "#: ";
cin >> n;
for(i = 1; i <= n; i++) {
//increase the divisor until it's equal to n
if(n % i == 0) {
count++;
}
//If there is no remainder, count increases by 1. Since prime numbers are only divisible by 1 and themselves, count will be exactly 2 in the case of a prime number.
}
if(count == 2) {
cout << " 1\n"; //1 = yes prime
}else if(count != 2) {
cout << " 0\n"; //0 = not prime
}
count = 0;
}
if(n == 'q') {
return(0);
}
}
여기서는 숫자를 테스트하여 소수인지 확인합니다. Count는 n/i의 나머지가 0 일 때마다 증가하므로 count = 2 인 경우 출력은 1, 그렇지 않은 경우 0입니다. 세션 중에 정확하게 원하는만큼의 숫자를 테스트하는 프로그램을 얻었지만 이스케이프 시퀀스를 만들려고합니다.대화 형 프로그램 끝내기 무한 루프가 발생합니다
종료 (n == 'q')를 사용하여 시도했지만 q를 입력하면 프로그램이 무한 루프됩니다. 나는 휴식을 취하려고했다. while 루프 내에서이 조건에 대한 설명이 있지만 결과는 같습니다. 이 문제는 char-int/int-char 변환과 관련이 있다고 생각합니다. 누군가 나에게 어떻게 작동 종료 시퀀스를 만들 수 있는지 알려 줄 수 있습니까?
종료 조건을 0이나 -1과 같이 프로그램에 적합하지 않은 특수한 숫자로 만들면 어떨까요? – perelman
가능한 [입력을받은 후 무한 루프가 C++에서 int인지 확인하기위한 루프] (http://stackoverflow.com/questions/8618473/infinite-loop-after-receiving-input-and-testing-to- –