int main()
{
int marks[3];
int counter=0;
for (i in marks){
printf(marks[i];
counter=counter+1;
}
return 0
}
对 C 很陌生,虽然我知道 Python。我不知道语法,但我正在尝试创建和数组,然后打印数组中的每个变量。我究竟做错了什么?
#include <stdio.h>
#define NUM_MARKS 3
int main()
{
int marks[NUM_MARKS];
/* marks contains all undefined data */
int counter=0;
int i;
for (i = 0; i < NUM_MARKS; i++){
printf("%d\n", marks[i]);
counter++;
}
return 0;
}
for
loop in C. See my example. And search google or SO.printf
line.;
after return 0
.printf
takes a string, not an int as it's first argument.
int main()
{
int marks[] = {1, 2, 3};
int i;
for (i = 0; i < 3; i++){
printf("%d", marks[i]);
}
return 0;
}
for (int i = 0; i < 3; i++)
assuming C99 support. Without C99 support,
int i;
for (i =0; i < 3; i++)
You can also use NUM_MARKS
in place of the 3:
enum { NUM_MARKS = 3 };
int marks[NUM_MARKS];
or:
enum { NUM_MARKS = sizeof(marks) / sizeof(marks[0]) };
The net result is the same.
C does not have foreach type loops as Python does. You can't just assume that language A works like language B. You need:
for(int i = 0; i < sizeof(marks) / sizeof(marks[0]); ++i) {
printf("%d\n", marks[i]);
}
If you're working in VS (and actually compiling as C) then you'll need to declare all of your variables at the top of the function. C99 changed this, but unfortunately MS will never support C99.