[英]My simple C program isn't compiling
I'm doing a small exercise for my C class and I'm getting difficulties I know shouldn't really be happening as these are supposed to take like 30 minutes max. 我正在为我的C级做一个小练习,我遇到的困难我知道不应该真的发生,因为这些应该花费最多30分钟。 Here is my program so far: 到目前为止,这是我的程序:
#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;
}
Here is the error I'm getting: 这是我得到的错误:
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”
As @ Inspired said there is an extra semicolon in the LIMIT
macro definition, that semicolon will be expanded by the preprocessor making this line 正如@ Inspired所说,在LIMIT
宏定义中有一个额外的分号,分号将由预处理器扩展,使得该行
for ( int num = 2; num <= LIMIT; num++ ) {
like this 像这样
for ( int num = 2; num <= LIMIT;; num++ ) {
/* ^^ 2 semicolons, now the num++ is extra */
but your program has yet another problem 但你的程序还有另一个问题
printf(num);
will not work, printf()
expects a format string and then the arguments so it should be 如果不起作用, printf()
需要一个格式字符串,然后是参数,所以它应该是
printf("%d\n", num);
You have an extra ;
你有一个额外的;
in #define LIMIT 1000000;
在#define LIMIT 1000000;
. 。
When handling #define
, compiler just performs a text substitution: it replaces LIMIT
with 1000000;
处理#define
,编译器只执行文本替换:它将LIMIT
替换为1000000;
. 。 So your for
loop looks like 所以你的for
循环看起来像
for (int num=2; num < 1000000 ;; num++)
^^
The second error happens because indeed printf
expects the first argument to be a string (format string), not an integer. 发生第二个错误是因为printf
期望第一个参数是字符串(格式字符串),而不是整数。 Eg printf("%d is prime.\\n", num);
例如printf("%d is prime.\\n", num);
( %d
is a placeholder for an integer value, and \\n
is end-of-line). ( %d
是整数值的占位符, \\n
是行尾)。
No semi-colon after LIMIT
define. LIMIT
定义后没有分号。 Processor directives don't get them so it is literally copying "100000;"
处理器指令没有得到它们所以它实际上是复制"100000;"
into the for loop. 进入for循环。
First argument of printf should be format string "%d"
so printf("%d\\n", num)
printf的第一个参数应该是格式字符串"%d"
所以printf("%d\\n", num)
Simple stuff you'll get used to (and still mess up when not thinking), but if you are just learning, it looks great. 你会习惯的简单东西(在不思考的时候仍然会陷入困境),但如果你只是在学习,它看起来很棒。 Far better than my first C programs. 远远超过我的第一个C程序。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.