[英]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”
你有一個額外的;
在#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.