结束交互式程序会导致无限循环

Ending an interactive program causes infinite loop

本文关键字:无限循环 交互式 程序 结束      更新时间:2023-10-16
//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(编译你的代码,让编译器警告你这样明显的东西。