瑞星卡卡安全论坛技术交流区系统软件 用C写的一个小游戏.有一点问题.大家来看下

1   1  /  1  页   跳转

用C写的一个小游戏.有一点问题.大家来看下

用C写的一个小游戏.有一点问题.大家来看下

用C写了一个猜数学的小游戏.程序默认一个数字为30.用户输入一个数字.如果是大于30,程序提示用户大了,如果小于30.程序提示小了.如果输为的为30则告诉用户赢了.
下面是源程序:
#include <stdio.h>
#define GOAL 30
void main()
{
int data;
int count;

count=0;
printf("please input the number:");
scanf("%d",&data);
do
{
if(data<GOAL)
printf("the number is small than GOAL");
else if(data>GOAL)
printf("the number is big than GOAL");
else
printf("you win");

count ++;
  }while(data!=GOAL);
printf("you have guess %d times ",count);
}



运行时发现当我输入数字时,结果非预期.出现很多代码.不停的刷屏.按任何键都没有用.是不是进了死循环.
我检查了程序,没有发现问题啊.有没有哪个看得出来其中的错误.
最后编辑2006-08-22 17:57:17
分享到:
gototop
 

#include <stdio.h>
#define GOAL 30
void main()
{
int data;
int count;

count=0;
printf("please input the number:");
scanf("%d",&data);
do
{
printf("please input the number:");
scanf("%d",&data);
if(data<GOAL)
printf("the number is small than GOAL");
else if(data>GOAL)
printf("the number is big than GOAL");
else
printf("you win");

count ++;
}while(data!=GOAL);
printf("you have guess %d times ",count);
}
现在程序可以执行正确了.
但是谁能告诉我将printf和scanf这两个语句写在do 内和do 外对结果的产生有什么区别吗?
我写在do内,程序正确完成任务.便是我写在外.则当我输入数学就出错.
期待高手给我一个完美的解答.
本人是初学C语言的.


gototop
 

是这句么?
printf("please input the number:");
scanf("%d",&data);

我认为do-while以外的可以不用,因为不存在变量不可控制的问题。如果使用while结构,在外部就必须加入这样的语句,才可保证程序的可控制性
gototop
 

楼上的可以举一个例子吗?
或许将那个语句写在do while 和do while外的运行过程给一个详细的解答吗?
我对可控性不是很理解.
gototop
 

我也想知道为什么我将那语句写在do while外.会在运行时,输入数据.却执行不了.为什么?
gototop
 

引用:
【粟子的贴子】楼上的可以举一个例子吗?
或许将那个语句写在do while 和do while外的运行过程给一个详细的解答吗?
我对可控性不是很理解.
...........................

举一个简单的例子
int j;
while(j==0)
{
scanf("%d",j);
..
}
..
在这里,j的值是不可控制的。因为程序只是为j开辟了内存空间,它的值是多少,我们不能控制。对于这种情况,可以通过变量的初始化来实现变量的可控性。

int j;
do
{
scanf("%d",j);
...
}while(j==0)
就不存在这个问题了,因为在判断j==0是否成立的时候,j的值已经是确定的了
gototop
 

我觉得你的代码,如果是第一种的话,可能会出现死循环
我认为这样好
do
{
printf("please input the number:");
scanf("%d",&data);
if(data<GOAL)
printf("the number is small than GOAL");
else if(data>GOAL)
printf("the number is big than GOAL");
else
printf("you win");

count ++;
}while(data!=GOAL);
gototop
 

天下奇才,可以告诉我你的QQ号吗?我想多请教你.可以吗?
gototop
 

我喷血啊~~~~~~~~~~
gototop
 
1   1  /  1  页   跳转
页面顶部
Powered by Discuz!NT