![](/img/trans.png)
[英]I'm having trouble trying to calculate the sum and average involving an array
[英]I'm having trouble with changing parts of an array
我目前正在开发一个在控制台中玩的小游戏。 我试图让玩家移动,但是当我尝试替换level
数组中的某个元素时,它会删除数组的 rest。
现在代码中唯一的移动是向右移动(在控制台中输入2
向右移动)
#include <iostream>
using namespace std;
#define con std::cout <<
#define newline std::cout << '\n'
#define text std::cin >>
#define end return 0
#define repeat while (true)
int width, height;
int rprog;
int x, y, z;
int playerpos;
int input;
double level[] =
{1, 1, 1, 1, 1, 1,
1, 0, 0, 0, 0, 1,
1, 0, 2, 0, 0, 1,
1, 0, 0, 0, 0, 1,
1, 0, 0, 0, 0, 1,
1, 1, 1, 1, 1, 1};
const char *display[] = {" ", "[ ]", "[X]"};
int render () {
x = 1;
y = 1;
while (x < 37) {
z = level[x - 1];
con display[z];
x = x + 1;
y = y + 1;
if (y == 7) {
y = 1;
newline;
}
}
end;
}
int player () {
con "Please make your next move : w: 1, a: 2, s: 3, d: 4";
newline;
con "Current position: " << playerpos;
newline;
text input;
if (input == 2) {
level[playerpos] = 0;
playerpos = playerpos - 1;
level[playerpos] = 3;
}
end;
}
int main() {
playerpos = 15;
while (true) {
render ();
player ();
}
end;
}
我目前正在使用这个网站进行编码: https://www.programiz.com/cpp-programming/online-compiler/
这是 output:
[ ][ ][ ][ ][ ][ ]
[ ] [ ]
[ ] [X] [ ]
[ ] [ ]
[ ] [ ]
[ ][ ][ ][ ][ ][ ]
Please make your next move : w: 1, a: 2, s: 3, d: 4
Current position: 15
2
[ ][ ][ ][ ][ ][ ]
[ ] [ ]
[ ]
然后它会切断关卡的渲染。
我很困惑。 我究竟做错了什么?
数组索引在 C++ 中以 0 开头。
您将新 position 处的项目设置为 3:
level[playerpos] = 3;
但是,显示类型的数组只有 3 个元素(0、1、2):
const char *display[] = {" ", "[ ]", "[X]"};
因此,您会遇到未定义的行为,因为您的访问权限越界。
另请注意,您的初始数组正确地为播放器 position 使用了2
,因此可以正常工作。
但是,它也有一个 off-by-1 错误:您初始化playerpos = 15
,但将2
放在索引 14 处。因此,初始渲染是错误的。 所以第一个动作不会是正确的,并且似乎停留在同一个position上。
正如@RemyLebeau 所提到的,你为什么在state 游戏中使用double
数组? 不仅其他类型更合适,尤其是double
会导致严重的、难以调试的问题。 并非所有整数都可以完美地用双精度表示,类型转换可能会导致不同的结果。
仅举一个例子:如果您添加状态 4 和 5,并想象一个 double 不能完全表示 5,而是将其存储为 4.99999999999999999。 访问数组时,integer 转换可能会呈现 state 4。 检查此问题和答案以获取详细信息
正如@KarenMelikyan 在评论中提到的那样,那些#define
是个坏主意。 它使您的代码更难被他人阅读,并且是一个不好的习惯。 最好熟悉正确的 C++ 语法并使用它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.