【发布时间】:2012-02-12 06:23:57
【问题描述】:
//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?
标签: c++ while-loop