2015-10-25 36 views
0

我必須在C語言中編寫函數來完成作業。 給定函數is_prime(n)和nth_prime(n),首先返回1,如果n是素數(或0,如果不是)和nth_prime返回第n個素數,我必須編寫函數next_prime(count)它被調用的時間,然後返回「count-th」數字素數。 count必須是一個靜態無符號整型變量。 如果n = 0(n用scanf給出),則計數值必須重置爲0,函數返回第一個素數2。
我不能使用結構,數組或遞歸。 我是新來的編碼,我不知道該怎麼做。 我使用Visual Studio 2010,我必須將它編譯爲ISO C89(ANSI C)。 這些函數必須寫入一個庫文件中,這是唯一要評估的東西,所以我不能在main()函數中使用count ++。 這是我迄今爲止所做的。在ISO C89中計數函數調用

unsigned int next_prime(unsigned int count) { 
    if(count == 0) { 
     if (n=!0) {      
      return nth_prime(count); 
      count++; 
     } else { 
      count = 0; 
      return 2; 
     }  
    } else {  
     if (n=!0) {      
      return nth_prime(count); 
     } else { 
      count = 0; 
      return 2; 
     }  
    } 
} 
+1

不應該'N = 0'是'N = 0'? – MikeCAT

+0

從創建靜態無符號整型變量'count'開始。 – MikeCAT

+0

我已經創建了它,但是我把它放在函數體外。 這是錯的嗎? 是的,這是n!= 0,我讓我誤會了。 我很抱歉。 – Luke

回答

0

這裏是一個將滿足你的問題的函數:!

/* the function next_prime(count) */ 
unsigned int next_prime(unsigned int count) { 
    /* avoid "unused parameter" warning */ 
    (void)count; 
    /* introduce this block because defining the variable count here will read to an redeclaring error */ 
    { 
     static unsigned int count = 0; 
     int n = -1; 
     /* n is given with a scanf */ 
     scanf("%d", &n); 
     /* if n=0 */ 
     if (n == 0) { 
      /* count value must be reset to 0 */ 
      count = 0; 
      /* return the first prime number, 2 */ 
      return 2; 
     } else { 
      /* count the time it is called */ 
      count++; 
      /* return the "count-th" prime number */ 
      return nth_prime(count); 
     } 
    } 
}