簡體   English   中英

我的簡單C程序沒有編譯

[英]My simple C program isn't compiling

我正在為我的C級做一個小練習,我遇到的困難我知道不應該真的發生,因為這些應該花費最多30分鍾。 到目前為止,這是我的程序:

#include <stdio.h>
#include <stdbool.h>
#define LIMIT 1000000;

bool isPrime( int num ) {
    for ( int factor = 2; factor * factor <= num; factor++ )
      if ( num % factor == 0 )
        return false;

    return true;
  }

int main() {
  for ( int num = 2; num <= LIMIT; num++ ) {
    if ( isPrime( num ) ) {
      printf( num );
    }
  }
  return 0;
}

這是我得到的錯誤:

primes.c: In function “main”:
primes.c:14: error: expected expression before “;” token
primes.c:16: warning: passing argument 1 of “printf” makes pointer from integer without a cast
/usr/include/stdio.h:361: note: expected “const char * restrict” but argument is of type “int”

正如@ Inspired所說,在LIMIT宏定義中有一個額外的分號,分號將由預處理器擴展,使得該行

for ( int num = 2; num <= LIMIT; num++ ) {

像這樣

for ( int num = 2; num <= LIMIT;; num++ ) {
                            /* ^^ 2 semicolons, now the num++ is extra */

但你的程序還有另一個問題

printf(num);

如果不起作用, printf()需要一個格式字符串,然后是參數,所以它應該是

printf("%d\n", num);

這個

你有一個額外的; #define LIMIT 1000000;

處理#define ,編譯器只執行文本替換:它將LIMIT替換為1000000; 所以你的for循環看起來像

for (int num=2; num < 1000000 ;; num++) 
                              ^^

發生第二個錯誤是因為printf期望第一個參數是字符串(格式字符串),而不是整數。 例如printf("%d is prime.\\n", num); %d是整數值的占位符, \\n是行尾)。

LIMIT定義后沒有分號。 處理器指令沒有得到它們所以它實際上是復制"100000;" 進入for循環。

printf的第一個參數應該是格式字符串"%d"所以printf("%d\\n", num)

你會習慣的簡單東西(在不思考的時候仍然會陷入困境),但如果你只是在學習,它看起來很棒。 遠遠超過我的第一個C程序。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM