我正在尝试一些练习来学习指针与数组和函数的使用。所以我尝试编写一种“奇怪的方式”来找出一定范围内的素数。
问题是输出总是将函数的返回值与素数算法相加。如果我省略它,它会显示'32767',如果我写return *pt,它会添加范围的最后一个数字,即使它不是素数!
刚刚用数字 6 试了一下:它不是素数,但它会弹出!
#include <iostream>
int show_primes(const int * begin, const int * end);
int main()
{
    using namespace std;
    int i = 0;
    int End_Array = 0;
    cout << "Write the last number in your range (it always start from number 2)";
    cin >> End_Array;
    i=End_Array;
    int cookies[i];
    for(i=-1; i<End_Array; i++)
       cookies[i] = i+1;
    cout << show_primes(cookies, cookies + End_Array-1);
}
int show_primes (const int * begin, const int * end)
{
    using namespace std;
    const int * pt;
    int z = 0;
    for (pt = begin; pt < end; pt++, z=0)
    {
        for (int n=2; n<=*pt; n++)
        if ( *pt%n == 0 )
            ++z;
        if (z==1)
            cout << *pt <<endl;
    }
    return *pt ;
}