-2
int i;
int b = 0;
int a[20];


for (i = 0; i < 20; i++){
a[i] = b+1;
cout << a[i];}



 }

//我知道这是一个简单的程序,但它没有给出预期的输出,也没有单步执行程序或打印出结果

4

3 回答 3

3

Your loop keeps assigning a[i] without changing b. Since b stays at zero, all as are going to be 1 (because b is zero, b+1 is 1).

If you would like to assign sequential values, either use the loop index i, or change b in the body of the loop:

for (i = 0; i < 20; i++) {
    a[i] = i+1;
}

or

for (i = 0; i < 20; i++) {
    a[i] = ++b; // Adds 1 to b, and changes b for the next iteration.
}
于 2013-07-13T03:04:37.103 回答
0

You are printing out the wrong variable. This should work:

int i;
int a[20];


for (i = 0; i < 20; i++){
a[i] = i+1;
cout << a[i];}
于 2013-07-13T03:05:22.320 回答
0

如果您希望通过以下方式分配,您可以这样做b

int i;
int b = 1;
int a[20];



for (i = 0; i < 20; i++){
a[i] = b;
cout << a[i];
b++;}
于 2013-07-13T03:13:16.217 回答