我写了一个 C++ 程序,打印所有小于 n
的素数,但程序在执行时一直崩溃。
#include <iostream>
using namespace std;
bool premier(int x) {
int i = 2;
while (i < x) {
if (x % i == 0)
return false;
i++;
}
return true;
}
int main() {
int n;
int i = 0;
cout << "entrer un entier n : ";
cin >> n;
while (i < n) {
if (n % i == 0 && premier(i))
cout << i;
i++;
}
;
}
最佳答案
作为Igor指出,当 n%i
完成时,i
第一次为零。由于您只需要质数,而最小的质数是 2,我建议您将 i
初始化为 2
而不是 0
。
您想打印所有小于 n
的素数,并且已经有一个检查素数的函数。
只是
while (i < n){
if ( premier(i) == true )
cout<<i;
i++;
}
并且在打印时,添加一些字符来分隔数字,以便能够像这样区分它们
cout<<i<<endl;
P.S:我认为您称其为 C++ 程序。不是脚本。
编辑:This您可能会感兴趣。
关于c++ - 在 C++ 中打印所有小于 n 的素数(文件崩溃),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46870260/