我正在嘗試一些練習來學習使用指針與數組和函數。 所以我試圖編寫一個「奇怪的方式」來找出一定範圍內的素數。C++不想要返回值
問題是,輸出總是添加函數的返回值與素數的算法。如果我忽略它,它顯示'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 ;
}
爲什麼這個功能需要一個返回值呢? – Chad
至少,寫入'cookies [-1]'會導致未定義的行爲。 –
其實我不太確定...但是如果你不放置返回值,會發生什麼是它增加'32767',我不知道它來自哪裏! – theskunk