1
int main()
{
int marks[3];
int counter=0;
for (i in marks){
     printf(marks[i];
         counter=counter+1;
}
return 0

}

对 C 很陌生,虽然我知道 Python。我不知道语法,但我正在尝试创建和数组,然后打印数组中的每个变量。我究竟做错了什么?

4

4 回答 4

5
#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;
}
于 2012-11-01T23:49:16.630 回答
2
  1. That's not how you do a for loop in C. See my example. And search google or SO.
  2. You missed a closing bracket on the printf line.
  3. You missed a semicolon ; after return 0.
  4. You didn't define any data in the array.
  5. 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;
    }
    
于 2012-11-01T23:48:57.637 回答
1
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.

于 2012-11-01T23:49:42.287 回答
1

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.

于 2012-11-01T23:50:25.447 回答