【发布时间】:2014-04-10 01:37:01
【问题描述】:
在这段代码中,我使用了一个整数数组,因为我觉得如果它们是整数,我正在处理的项目会容易得多。在这个数组中,我将每个位置分配给 46(ASCII 表示 '.')并打印出该 ASCII 的 (char) 版本。我将板子设置为 int 的原因是因为我将在此板上放置数字,但我想保持“。”我打印的。
电流输出:
. . . . .
. . . . .
. . . . .
. . . . .
☺ . . . .
期望的输出:
. . . . .
. . . . .
. . . . .
. . . . .
1 . . . .
使用 (char) 进行强制转换将打印 '.' (ASCII 46)很好,但我的数字会被扭曲,正如当前输出所指示的那样。
我该如何解决这个问题?我一直盯着这个看。
我的代码:
using namespace std;
#include <stdlib.h>
#include <iostream>
#include <time.h>
#include <math.h>
void addRandomNumberToBoard(int *board, int &arrSize)
{
srand ((int)time(0)); //seed random
int destination;
do destination= rand() % (arrSize-1);
while ( board[destination] != '.'); // place on a random spot on the board
int randomNumber=rand() < RAND_MAX / 2 ? 1 : 2; //generate number 1 or 2
board[ destination] = randomNumber; //place the number there
}
int printBoard(int &i, int &arrSize, int *board)
{
for(i=0; i<arrSize; i++)
{
if( i % 5 == 0 && i!=0) //after every 5 positions print a new line
cout<<"\n\n";
cout<<" "<<(char)board[i]; //this MIGHT be the problem
}
}
int main()
{
int i;
int arrSize=25;
int board[arrSize];
for(i=0; i<arrSize; i++) //declare all positions as ASCII '.'
board[i]='.'; //this MIGHT be the other problem
addRandomNumberToBoard(board,arrSize);
printBoard(i, arrSize, board);
}
【问题讨论】:
-
假设我正在制作一个类似于 2048 的游戏。char 数组将无法容纳大于 8 的数字,所以我将使用 int 数组
标签: c++ arrays integer character