题目如下
标题:贪吃蛇长度
+-------------------------------------------------+
| |
| H###### #### |
| # # # |
| # # # |
| # #### # # |
| # # # # # |
| ######@### # # |
| # #### # # |
| # # # # # |
| ####@#######@### # # |
| # # # # # |
| T ##### # # # ## |
| # # ### ### ## |
| ################ # # #### |
| # # # # |
| ############## #######@########## |
| # ### |
| ########################### |
+-------------------------------------------------+
小明在爷爷的私人收藏馆里找到一台老式电脑。居然没有图形界面,只能用控制台编程。
经过小明的一阵摸索,神奇地设计出了控制台上的贪食蛇游戏。
如上图,是游戏时画面截图。
其中,H表示蛇头,T表示蛇尾。#表示蛇的身体,@表示身体交叉重叠的地方。
你能说出现在的贪吃蛇长度是多少吗?
其实,只要数出#的数目算1,数出@的数目,算2,再加上头尾各算1就计算好了。
人工数一下?太累眼睛了,聪明的你为什么不让计算机帮忙呢?
本题的要求就是: 请填写上图中贪食蛇的长度是多少?
注意:需要提交的是一个整数,不要添加任何多余内容(比如说明或注释)
正确答案:190个
C语言版本代码如下:
#include <stdio.h>
#include <stdlib.h>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int main(int argc, char *argv[])
{
int length = 0;
char ch;
FILE *fp;
if((fp = fopen("txt1.txt","r"))==NULL)
{
printf("cannot open this file\n");
exit(0);
}
while(!feof(fp))
{
ch = fgetc(fp);
if(ch == '#'|| ch == 'H' || ch == 'T')
{
length++;
}
else if(ch == '@')
{
length += 2;
}
}
fclose(fp);
printf("The length of the snake if %d",length);
return 0;
}
在这之前,我一直有错误,读取到的长度比实际的小,为106。
错误的程序如下:
#include <stdio.h>
#include <stdlib.h>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int main(int argc, char *argv[])
{
int length = 0;
//char ch;
FILE *fp;
if((fp = fopen("txt1.txt","r"))==NULL)
{
printf("cannot open this file\n");
exit(0);
}
while(!feof(fp))
{
/*
ch = fgetc(fp);
注意区别,我这里没有用中间变量ch,相当于一个if判断执行了3次fgetc(fp)
而fgetc()函数每调用一次,指针就后移一个字符的位置,
所以读取的字符总是比实际少。
*/
if(fgetc(fp) == '#'|| fgetc(fp) == 'H' || fgetc(fp) == 'T')
{
length++;
}
else if(fgetc(fp) == '@')
{
length += 2;
}
}
fclose(fp);
printf("The length of the snake if %d",length);
return 0;
}
接着下面附上一位博主的C++版本代码,今天(19年3月23日)发现我忘记加那位博主的博客链接了,找了一会儿,还是没找到,对此表示抱歉:
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
int main(int argc,char** argv){
ifstream fin;
fin.open("txt1.txt");
int nums = 0;
while(fin){
char data;
fin >> data;
if(data == '#'){
nums++;
}else if(data == '@'){
nums = nums + 2;
}else if(data == 'T' || data == 'H'){
nums++;
}
}
cout << nums;
}
如果你用Windows自带的记事本打开,你会发现“游戏画面截图”竟然是这个样子的,这玩意怎么也不像个贪吃蛇啊,这是记事本对tab键显示的问题,我怀疑记事本把所有空白字符都显示为一个空格,所以……咳咳,你还在为写代码时有tab还是空格而纠结吗,当然是空格啦,什么编辑器都不会出错,如果是tab,最好设置为将tab替换为四个空格。
贪吃蛇界面由于是记事本显示的问题,所以看不出贪吃蛇的轮廓,下面为notepad上查看的。