c++ - for循环错误计算素数C++

标签 c++ visual-c++

我正在尝试学习如何编码,但在尝试了解我的代码有什么问题时我很挣扎。我正在使用 C++ 中的 Visual Studio 2013 进行编程。

问题:编写一个程序,从用户那里读取一个数字 N,然后找到前 N 个质数。质数是只有两个约数的数,一个和它本身。

我的代码没有打印出一系列素数,而是重复了一些素数。

#include <iostream>
using namespace std;
// this program will calculate the first N primes


int main(){

    int N;
    cin >> N;

    for (int i = 2; i < N; i++){
        for (int j = 2; j < N; j++){

            if (i%j == 0){
                break;

            }
            else
                cout << i << " " << "is a prime number\n";
        }       
    }
}

最佳答案

只要 j 不整除 i,您就会打印出 i 是质数。您应该等到检查完所有 可能的除数。我不会给你应该做什么的答案,但它应该涉及修改你的代码的这一部分:

if (i%j == 0){
break;

}
else
cout << i << " " << "is a prime number\n";
}       

关于c++ - for循环错误计算素数C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23189806/

相关文章:

c++ - 可以使用 pdcurses 编辑任何 Windows 终端的调色板吗?

c++ - 无法初始化某些指针,在运行时中断程序

c++ Vector fetch方法在Release中返回nullptr但在Debug中不返回

windows - 通过 INPUT 结构发送 Ctrl Alt Del 不起作用?

windows - 启用 ctreecntrl 树项中的复选框

c++ - libthrift-0.9.1.so : cannot open shared object file: No such file or directory

c++ - 或无效 C++ : why does this code compile?

c# - 如何在 C# 中返回字符串列表

c++ - make_unique 给出错误 2248

windows - 如果从静态库调用,Atl CDialogImpl 不会显示在 DoModal 上