0

这是我正在编写的数组的一些基本代码。我需要用 4 填充数组的所有插槽 (14),然后编写一个循环,将插槽 6 和 13 替换为 0。我是初学者,还没有学习矢量,只是基本的编程材料。

const int MAX = 14;

int main ()
{

    board ();
    cout<<endl;

    {


        int i;
        int beadArray[MAX] = {4};

        for (i = 0; i < MAX; i++)
        {
            beadArray[i] = -1;
        }

        for (i = 0; i < MAX; i++)
        {
             cout<<i<<"\t";
        }
     }


    cout<<endl;
    system("pause");
    return 0;
}
4

2 回答 2

3
#include <iostream>
#include <cstdlib>
using namespace std;

int main(){

    //this constant represents the size we want our array to be
    //the size of an array must be determined at compile time.
    //this means you must specify the size of the array in the code.
    const unsigned short MAX(14);

    //now we create an array
    //we use our MAX value to represent how large we want the array to be
    int beadArray[MAX] = {4};

    //now our array looks like this:
    //+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
    //| 4 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 |
    //+---+---+---+---+---+---+---+---+---+---+---+---+---+---+

    //but you want each index to be filled with 4.
    //lets loop through each index and set it equal to 4.
    for (int i = 0; i < MAX; ++i){
        beadArray[i] = 4;
    }

    //now our array looks like this:
    //+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
    //| 4 | 4 | 4 | 4 | 4 | 4 | 4 | 4 | 4 | 4 | 4 | 4 | 4 | 4 |
    //+---+---+---+---+---+---+---+---+---+---+---+---+---+---+

    //to set slots 6 and 13 equal to 0, it is as simple as this:
    beadArray[6] = 0;
    beadArray[13] = 0;

    //careful though, is that what you wanted?
    //it now looks like this:
    //+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
    //| 4 | 4 | 4 | 4 | 4 | 4 | 0 | 4 | 4 | 4 | 4 | 4 | 4 | 0 |
    //+---+---+---+---+---+---+---+---+---+---+---+---+---+---+

    //this is because the [index number] starts at zero.

    //index: 0   1   2   3   4   5   6   7   8   9   10  11  12  13
    //     +---+---+---+---+---+---+---+---+---+---+---+---+---+---+
    //     | 4 | 4 | 4 | 4 | 4 | 4 | 4 | 4 | 4 | 4 | 4 | 4 | 4 | 4 |
    //     +---+---+---+---+---+---+---+---+---+---+---+---+---+---+


    //print out your array to see it's contents:
    for (int i = 0; i < MAX; i++){
        cout << beadArray[i] << " ";
    }

    return EXIT_SUCCESS;
}
于 2012-04-25T04:11:27.617 回答
0

你可以做这样的事情

int beadArray[14];
for(int i=0;i<14;i++){
    beadArray[i]=4;
}
beadArray[6]=0;
beadArray[13]=0;

或者

int beadArray[14];
for(int i=0;i<14;i++){
    if(i==6 || i==13)
        beadArray[i]=0;
    else
        beadArray[i]=4;
}
于 2012-04-25T03:58:47.230 回答