#include
void fun(int m, int k, int xx[])
{
int j,n=0,a,b=0;
while(n<k)
{
a=m+1;
for(j=1;j<a;j++)
{
if(a%j==0)
b++;
}
if(b==0)
xx[n++]=a;
}
xx[n]=0;
}
main()
{
int m, n, zz[1000] ;void NONO ();
printf("\nPlease enter two integers:");
scanf("%d %d", &m, &n);
fun(m, n, zz);
for(m = 0 ; m < n ; m++)
printf("%d ", zz[m]);
printf("\n");
NONO();
}
void NONO ()
{/* 本函數用於打開文件,輸入測試數據,調用fun函數,輸出數據,關閉文件。*/
int m, n, zz[1000], i ;
FILE *rf, *wf ;
rf = fopen("in.dat","r");
wf = fopen("out.dat","w");
for(i = 0 ; i < 10 ; i++) {
fscanf(rf, "%d %d", &m, &n);
fun(m, n, zz);
for(m = 0 ; m < n ; m++) fprintf(wf, "%d ", zz[m]);
fprintf(wf, "\n");
}
fclose(rf);
fclose(wf);
}
有以下幾點不對:
1.fun()函數不對,有死循環,每次a都等於m+1,
//你的邏輯
void fun(int m, int k, int xx[])
{
int j,n=0,a,b=0;//這裡一大堆錯,b不能放在循環外面,否則b永遠不可能為0,a每次要++
while(n<k)
{
a=m+1;
for(j=1;j<a;j++)
{
if(a%j==0)
b++;
}
if(b==0)
xx[n++]=a;
}
xx[n]=0;
}
//該進之後
void fun(int m, int k, int xx[])
{
if (NULL == xx || m <= 0 || k <= 0)
{
return;
}
int a = m + 1;
int n = 0;
if (1 == m)
{
xx[n++] = 2;
a++;
}
while(n < k)
{
int j;
int b = 0;
for(j = 2;j < a;j++)//從2開始
{
if((a%j) == 0)
{
b++;//一次不滿足直接退出;
break;
}
}
if(b == 0)
{
xx[n++]=a;
}
a++;
}
xx[n]=0;
}
//我的版本
void fun(int m, int k, int xx[])
{
if (NULL == xx || m <= 0 || k <= 0)
{
return;
}
int iCount = 1;
while (k > 0)
{
int iTemp = m + iCount;
if (2 == iTemp)
{
*xx++ = iTemp;
k--;
}
else if (1 == (iTemp & 1))
{
iTemp = (iTemp + 1) / 2;
while (iTemp >= 2)
{
if (0 == ((m + iCount)%iTemp))
{
break;
}
iTemp--;
}
if (1 == iTemp)
{
*xx++ = m + iCount;
k--;
}
}
iCount++;
}
*xx = 0;
}
2.文件流操作不對,這個不多說,不是重點