yapony 2022-02-26 12:15 采纳率: 25%
浏览 42
已结题

lifegame的c语言实现

进行了几个函数的拆分,分为初始化,显示,是否选择继续,相邻格子存活个数和更新代数几个部分,但运行时主函数每次运行到初始化startup()处便停止了,也无法进行输入,这是为什么?
行和列用作全局变量。codeblocks编程

#include <stdio.h>
#include <stdlib.h>

#define Height 20
#define Width 60
int grid[Height+2][Width+2];
int newgrid[Height+2][Width+2];
int Count[Height+2][Width+2];
int row,col;

void startup(){
   for(row=0;row<=Width+1;row++){
    for(col=0;col<=Height+1;col++){
       grid[row][col]=0;}}
   printf("List the coordinates for living cells.\nTerminate the list with the special pair -1 -1\n");
   scanf("%d %d",&row,&col);
   while(row!=-1||col!=-1){
    if(row>=1&&row<=Width){
        if(col>=1&&col<=Height)
            grid[row][col]=1;
            else printf("column %d is out of range.\n",col);}
    else printf("row %d is out of range.\n",row);
    scanf("%d %d",&row,&col);
   }
}

void show(){
   printf("The current life generation is:\n");
   for(row=1;row<=Width;row++){
    for(col=1;col<=Height;col++){
        if(grid[row][col]=1)printf("*");
        else printf("-");}
    printf("\n");
    }
    printf("\n");
}

int yes_or_no(){
   char ans;
   printf("Continue viewing new generations?\n(y,n)?");
   scanf("%c",&ans);
   while(ans!='y'||'Y'||'n'||'N'){
   printf("respond with either y or n:\n");
   scanf("%c",&ans);}
   if(ans=='y'||'Y')return 1;
   else return 0;
}
void neighbor_count(){
    int i,j;
    int count=0;
    for(row=1;row<=Width+1;row++){
    for(col=1;col<=Height+1;col++){
    for(i=row-1;i<=row+1;i++)
        for(j=col-1;col+1;j++)
        count+=grid[i][j];
    count-=grid[i][j];
    Count[row][col]=count;}}
}

void update(){
   for(row=1;row<=Width;row++)
    for(col=1;col<=Height;col++)
    switch(Count[row][col]){
   case 2:
    newgrid[row][col]=grid[row][col];break;
   case 3:
    newgrid[row][col]=1;break;
   default:
    newgrid[row][col]=0;break;
    }
    for(row=1;row<=Width+1;row++)
        for(col=1;col<=Height+1;col++)
        grid[row][col]=newgrid[row][col];

}

int main(){
   printf("Welcome to Conway's game of Life.\nThis game uses a grid of size 20 by 60 in which\neach cell can either be occupied by an organism or not.\n");
   printf("The occupied cells change from generation to generation\naccording to the number of neighboring cells which are alive.\nList the coordinates for living cells.\nTerminate the list with the special pair -1 -1\n");
   startup();
   show();
   while(yes_or_no()){
   neighbor_count();
   update();
   show();
   yes_or_no();}
   return 0;
}



  • 写回答

1条回答 默认 最新

  • 易水卷长空 2022-02-26 14:42
    关注

    scanf格式控制符之间不需要空格

    scanf("%d%d",&row,&col);
    
    评论

报告相同问题?

问题事件

  • 已结题 (查看结题原因) 2月27日
  • 创建了问题 2月26日

悬赏问题

  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料