Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/eclipse/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
打印给定数字范围内的素数。我无法使代码正常工作 我试图用C++编写一个程序,在一个范围内找到质数。例如:_C++ - Fatal编程技术网

打印给定数字范围内的素数。我无法使代码正常工作 我试图用C++编写一个程序,在一个范围内找到质数。例如:

打印给定数字范围内的素数。我无法使代码正常工作 我试图用C++编写一个程序,在一个范围内找到质数。例如:,c++,C++,起始范围的输入编号:1 结束范围的输入编号:100 介于1和100之间的素数是: 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 这是我的实际代码,我不知道为什么它不工作。如果可能的话,您能在不添加任何新变量的情况下编辑代码吗 int nr1; int nr2; bool check = true; cin >> nr1; cin >> nr2; for (int x = nr1

起始范围的输入编号:1
结束范围的输入编号:100
介于1和100之间的素数是:
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97

这是我的实际代码,我不知道为什么它不工作。如果可能的话,您能在不添加任何新变量的情况下编辑代码吗

int nr1;
int nr2;
bool check = true;
cin >> nr1;
cin >> nr2;
for (int x = nr1; x <= nr2; x++)
{
    for (int y = 2; y < x; y++)
    {
        if (x % y == 0)
        {
          check = false;
        }
    }
    if (check)
    {
        cout << x;
    }
    else
    {
        cout << " ";
    }
}
intnr1;
int-nr2;
布尔检查=真;
cin>>nr1;
cin>>nr2;

对于(int x=nr1;x而言,您的代码几乎没有问题,但经过修复后,对于大量性能而言,它不是最佳的。这是一个更新和更新注释最少的版本:

int nr1;
int nr2;

bool check = true;
cin >> nr1;
cin >> nr2;

// must start from 2 if start is less than 2
if(nr1 < 2) {
    nr1 = 2;
}

for (int x = nr1; x <= nr2; x++) {
    // bring it inside loop
    check = true;

    // this is fine, but condition "y * y <= x" would be faster
    // also you repeat this check for all numbers
    // if you keep previous primary numbers in memory
    // you can loop only primary numbers
    for (int y = 2; y < x; y++) {
        if (x % y == 0) {
            check = false;
        }
    }

    // minor format fix
    if (check) {
        cout << x << " ";
    }
}

// minor format fix
cout << endl;
intnr1;
int-nr2;
布尔检查=真;
cin>>nr1;
cin>>nr2;
//如果起始值小于2,则必须从2开始
如果(nr1<2){
nr1=2;
}

对于(intx=nr1;x)解释它是如何工作的。非常感谢Anatoliy R!代码工作得非常好。