从存储的值输出数组值不同 [英] Outputted array values different from the values stored

查看:102
本文介绍了从存储的值输出数组值不同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我做了一个数组,并从1值设置为在 initializeBoard 功能9,但由于某些原因,当我打印值就出来0至8.为什么出现这样的情况?难道不应该打印出1到9,因为这些都是我把阵列中 initializeBoard

号码

  INT的main()
{
    initializeBoard();
    ticTacToeBoard();
}无效initializeBoard()
{
    的for(int i = 1; I< 9;我++)
        ticTacBoard [我] =我;
    COUT<< ENDL;
}无效ticTacToeBoard()
{
    为(中间体Y = 0; Y 3;; Y +)
    {
        为(中间体X = 0; X 3;; X ++)
            COUT<< ticTacBoard [3 * Y + X]<< ;
        COUT<< ENDL;
    }
}


解决方案

您有一个关闭逐有一个错误。阵列使用在C ++从零开始的索引。您code不的数组元素的值赋给零。

试试这个:

 的for(int i = 0; I< 9;我++)
{
    ticTacBoard [I] = i + 1的;
}

I made an array and set the values from 1 to 9 in the initializeBoard function, but for some reason when I print the values they come out 0 to 8. Why is this happening? Shouldn't it print out 1 to 9 since those are the numbers I put in the array in initializeBoard?

int main()
{
    initializeBoard();
    ticTacToeBoard();
}

void initializeBoard()
{
    for (int i = 1; i < 9; i++)
        ticTacBoard[i] = i;
    cout << endl;
}

void ticTacToeBoard ()
{
    for (int y = 0; y < 3; y++)
    {
        for (int x = 0; x < 3; x++)
            cout << ticTacBoard[3 * y + x] << " ";
        cout << endl;
    }
}

解决方案

You have an off-by-one error. Arrays use zero-based indexing in C++. Your code does not assign a value to the zeroth element of the array.

Try this instead:

for (int i = 0; i < 9; i++)
{
    ticTacBoard[i] = i + 1;
}

这篇关于从存储的值输出数组值不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆