结束交互式程序会导致无限循环
Ending an interactive program causes infinite loop
//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 << " 1n"; //1 = yes prime
}else if(count != 2) {
cout << " 0n"; //0 = not prime
}
count = 0;
}
if(n == 'q') {
return(0);
}
}
在这里,我正在测试数字,看看它们是否是素数。每次除法 n/i 的余数为 0 时,计数都会增加,因此当 count=2 时,输出为 1 表示是,否则为 0 表示否。我已经让程序在会话期间正确测试任意数量的数字,但我正在尝试创建一个转义序列。
我尝试使用条件 (n=='q'( 退出,但是当我输入 q 时,程序无限循环。我试着休息一下;在 while 循环中对此条件的语句,但结果是相同的。我猜这个问题与字符/字符转换有关。有人可以提示我如何创建有效的退出序列吗?
您没有可以读取q
的代码。您的输入逻辑仅接受数字。然后测试该数字是否等效于q
字符。字母 q
的等效整数为 113。如果你尝试这样做,它会退出。
由于您确实想输入数字或字母,因此您需要编写可以接受其中任何一个的输入逻辑。然后,您需要检查您获得的输入,然后相应地处理它。
'q' 是一个字符。 n
是一个整数。
检查n == 'q'
是否会隐式将"q"转换为int
类型 - 因此,如果您输入数字 113(ASCII 表示"q"(,您的程序将退出。
您可能希望使用超出常规输入范围的数字(例如负值或零(作为终止条件。
旁注:在while
循环中检查n
之前,您没有初始化它。n
有可能从任何随机垃圾开始,因此在一定比例的情况下,您的程序将自发退出而不运行循环。你应该用-Wall -Wextra
(如果使用gcc
(编译你的代码,让编译器警告你这样明显的东西。
相关文章:
- 过载'operator new'如何导致无限循环?
- C++正则表达式无限循环
- 程序在尝试猜测它选择的随机数时进入无限循环?
- 遍历链表时的无限循环
- 循环链表:无限循环
- 比较两个字符串后卡在无限循环中
- 在做一段时间内检查字符的无限循环
- 逐字读取文本文件中的每一行并转换为 int(无限循环或崩溃?
- 在这个无限循环中,当输入 0 时终止,当输入 int 范围之外的任何内容时,程序行为不正常
- 可能的无限循环
- 超出 int 的值范围后的无限循环
- 为什么这段代码会导致无限循环?
- 运行无限循环的最小二叉树问题
- 在分配和发布递增循环迭代器时C++无限循环(gcc 错误?
- 连接线程时的无限循环
- 为什么这种方法会进入无限循环?
- 由于QTextStream的无限循环
- Qt 在另一个线程中无限循环
- 从文件 C++ 读取时的无限循环
- 结束交互式程序会导致无限循环