简体   繁体   English

C ++程序查找素数并自行计时

[英]C++ Program Finding Prime Numbers and Timing itself

I am trying to write a c++ program that finds n prime numbers and times itself. 我正在尝试编写一个查找n个质数和其自身时间的c ++程序。 I have already done this in 5 other languages using this logic. 我已经使用此逻辑以其他5种语言完成了此操作。 For some reason, this code does nothing. 由于某种原因,此代码不执行任何操作。 I am using the Code Blocks compiler. 我正在使用代码块编译器。 What causes this code not to work and how can I fix it? 是什么导致该代码无法正常工作,我该如何解决? I am not very familiar with c++ so it will probably be something trivial. 我对c ++不太熟悉,因此可能很简单。

#include <iostream>
#include <math.h>
int main(){
    int n=10;
    int b=new int[n];
    int c=0;
    int d=2;
    while(c<n){
        bool e=true;
        for(int i=0;i<c;i++){
            if(d<sqrt(b[i])){
                break;
            }
            if(d%b[i]==0){
                e=false;
                break;
            }
        }
        if(e){
            b[c]=d;
            c++;
        }
        d++;
    }
    for(int i=0;i<c;i++){
        cout << b[i]+"\n" << endl;
    }
}

Several issues: 几个问题:

int b=new int[n];
   //^^compile error

should be 应该

int* b=new int[n];  //also need initialize array b

Meanwhile: 与此同时:

if (d<sqrt(b[i]))

You should initialize b before you try to access it. 在尝试访问b之前,应先对其进行初始化。

besides: 除了:

cout << b[i]+"\n" << endl;

EDIT: @Daniel Fischer, this would compile with std:: added before cout and endl , but will result in undefined behavior. 编辑: @Daniel Fischer,这将与std::一起编译,并在coutendl之前添加,但是会导致未定义的行为。 try: 尝试:

cout << b[i] << endl;

if you want to print b[i] s only. 如果只想打印b[i]

Additionally, inside your while loop, you need to increment c after b[c] = d , otherwise, it is going to the element into the same index again and again. 另外,在while循环内,您需要在b[c] = d之后递增c ,否则,它将一次又一次地将元素移到相同的索引中。

int b should be declared as int *b int b应该声明为int *b

You need to add using namespace std if you want to use cout etc. without namespace prefixes. 如果要使用不带名称空间前缀的cout等,则需要using namespace std添加。 With prefixes you can do std::cout. 使用前缀,您可以执行std :: cout。

Also you've got an infinite loop because c is never incremented. 另外,由于c永远不会递增,因此您会遇到无限循环。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM