//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 时计数增加,因此当计数 = 2 时,输出为 1 表示是,否则输出为 0。我已经让程序在 session 期间正确测试尽可能多的数字,但我正在尝试创建一个转义序列。
我尝试使用条件 (n=='q') 退出,但是当我输入 q 时,程序会无限循环。我试着休息一下;在 while 循环中声明此条件,但结果是相同的。我猜这个问题与 char-int/int-char 转换有关。有人可以提示我如何创建有效的退出序列吗?
最佳答案
您没有可以读取 q
的代码。您的输入逻辑只接受一个数字。然后测试该数字是否等同于 q
字符。字母 q
的等效整数是 113。如果您尝试这样做,它将退出。
因为您确实想输入一个数字或一个字母,您需要编写可以接受其中任何一个的输入逻辑。然后你需要检查你得到了什么输入,然后相应地处理它。
关于c++ - 结束交互式程序会导致无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9246914/