gpt4 book ai didi

C 数组的值随机变化

转载 作者:行者123 更新时间:2023-11-30 18:18:03 26 4
gpt4 key购买 nike

好吧,我一直在开发一个像胭脂一样的小游戏来自学 c,但是我无法弄清楚为什么数组在初始化后最终会随机变化。这是我的代码:

// ConsoleApplication2.cpp : Defines the entry point for the console application.
//


#include "stdafx.h"
#include <stdio.h>
#include <conio.h>
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>

const int x=10;
const int y=10;

int rexit[]={5,5};
int player[]={1,1};
int enemy[]={x,y};
int useless[]={1,1};




/*
int getinput(int len){
char temp[100];
return(atoi(strtok(fgets(temp,len+1,stdin),"\n")));

}
*/


void bad(){
float bob;
float temp[8]={1,1};
temp[1]=player[1]-enemy[1];
temp[2]=player[2]-enemy[2];
bob=pow(temp[1],2)+pow(temp[2],2);
printf("%f\n",bob);

if (sqrt(bob)<=5){
if (abs(player[1]-enemy[1])>abs(player[2]-enemy[2])){
if (player[1]-enemy[1]<0 && enemy[1]-1>=0){
enemy[1]=enemy[1]-1;
}
else if (enemy[1]+1<=x && player[1]-enemy[1]!=0){
enemy[1]=enemy[1]+1;
}
}
else;
if (player[2]-enemy[2]<0 && enemy[2]-1>=0){

enemy[2]=enemy[2]-1;
}
else if (enemy[2]+1<=y && enemy[2]-player[2]!=0){
enemy[2]=enemy[2]+1;
}
}
}

void map() {
int s;
int a;
bad();
printf("%i %i\n",rexit[1],rexit[2]);
printf("+");
for (a=0;a<=x;a++){
printf("-");
}

printf("+\n");
for (s=0;s<=y;s++){
printf("|");
for (a=0;a<=x;a++){
if ((player[1]==rexit[1] && player[2]==rexit[2]) || (player[1]==enemy[1] & player[2]==enemy[2])){
exit(EXIT_SUCCESS);
}
else if (rexit[1]==s && rexit[2]==a){
printf("E");
}
else if (player[1]==s && player[2]==a){
printf("*");
}
else if (enemy[1]==s && enemy[2]==a){
printf("@");
}
else{
printf(".");
}
}
printf("|\n");
}
printf("+");
for (a=0;a<=x;a++){
printf("-");
}

printf("+\n");
}


void move(){
char me=_getch();
int temp=0;

me=toupper(me);
if (me=='W'){ player[1]=player[1]-1; if (player[1]<=0) player[1]=0;}

else if (me=='S'){ player[1]=player[1]+1; if (player[1]>=y) player[1]=y;}

else if (me=='A'){ player[2]=player[2]-1; if (player[2]<=0) player[2]=0;}

else if (me=='D'){ player[2]=player[2]+1; if (player[2]>=x) player[2]=x;}

else {temp=1;}
if (temp==1){
move();}
else{
system("cls");
map();}
}


void circle(char c,int x)
{
int i,j;
for(i=-x;i<x;i++)
{
for(j=-x;j<x;j++)
{
if(i*i+j*j<x*x)
printf("%c",c);
else
printf(" ");

}
printf("\n");
}
}



void main(){
printf("%i %i\n",enemy[1],enemy[2]);
printf("%i %i\n",useless[1],useless[2]);
system("title BioGames");
system("color A"); // the colours are from 1 to 15

map();
while (true){
move();
}

}

最佳答案

您将数组索引视为从 1 开始。 C 中的数组是从 0 开始的。

例如,您声明:

int player[]={1,1};

此数组的唯一有效索引是 0 和 1( player[0]player[1])。

不存在诸如 player[2] 这样的东西 - 访问数组边界之外的内存。这可能就是您认为数组随机变化的原因。它们要么受到对其他数组的越界写入的影响,或者您只是遇到未定义的行为

关于C 数组的值随机变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18564142/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com