繁体   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