//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);
}
}
在這裏,我正在測試數字,看看它們是否是素數。每次除數n/i的餘數爲0時計數都會增加,因此當count = 2時,輸出爲1表示否,否則爲0。我已經得到程序在會話期間測試儘可能多的數字,但我試圖創建一個轉義序列。結束互動程序導致無限循環
我嘗試使用條件(n =='q')退出,但是當我輸入q時,程序無限循環。我試着休息一下;語句在while循環內但是結果是相同的。我猜這個問題與char-int/int-char轉換有關。有人可以向我暗示我如何創建工作退出序列?
爲什麼不讓你的退出條件成爲一個特殊的數字,對你的程序來說沒有意義,比如0或-1? – perelman 2012-02-12 06:30:21
可能重複[無限循環後接收輸入和測試,看看它是否是一個int在C + +](http://stackoverflow.com/questions/8618473/infinite-loop-after-receiving-input-and-testing-to-請參閱if-it-int-in-c) – 2012-02-12 06:55:11