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. 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
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("%d\n", num);
read this
You have an extra ;
in #define LIMIT 1000000;
.
When handling #define
, compiler just performs a text substitution: it replaces LIMIT
with 1000000;
. So your for
loop looks like
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. Eg printf("%d is prime.\\n", num);
( %d
is a placeholder for an integer value, and \\n
is end-of-line).
No semi-colon after LIMIT
define. Processor directives don't get them so it is literally copying "100000;"
into the for loop.
First argument of printf should be format string "%d"
so 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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.