将if语句与do while结合使用

时间:2014-04-22 09:15:17

标签: c

我正在完成一个小游戏,其中第一项任务是检查input > 0input < 23

int height;

do
{
   printf("Height: ");
   height = GetInt();
}
while((height <= 1) || (height > 23));

这很有效。键入不符合语句的值时,必须键入新值。但是我也希望在if语句中包含类似的内容:

if while (condition is not true)
{
    printf("Fill in a number between 1-23!")
}

但是不能让这个工作。有人知道我做错了什么?

4 个答案:

答案 0 :(得分:2)

写反向:

int height = -1; //DEFAULT VALUE LET ME JUMP RIGHT INTO THE WHILE LOOP
while((height <= 1) || (height > 23)) {

    //IMMEDIATELY PRINT MESSAGE ABOUT ACCEPTABLE RANGE OF VALUES
    printf("Fill in a number between 1-23");  

    //READ A VALUE
    height = GetInt();
    printf("Height: ");
}

答案 1 :(得分:0)

由于printf始终返回打印的字符数,因此在此情况下,它必须为非零,即true

因此,您可以使用以下内容替换while条件:

do {
  /* get input */
}
while(((height <= 1) || (height > 23)) && printf("Fill in a number between 1-23\n"));

如果条件的前半部分为false,则不会执行printf部分,并且循环退出。如果上半部分为trueheight超出范围),则printf部分将被执行并评估为true

答案 2 :(得分:-1)

我想你想这样做:

int height = -1;// Default Value
do
{
   printf("Height: ");
   height = GetInt();// get  int value
   if(!((height <= 1) || (height > 23))) // check condition
   {
    printf("Fill in a number between 1-23"); 
    break; // break loop
   }

}while((height <= 1) || (height > 23));

希望这会帮助你......

答案 3 :(得分:-1)

使用布尔标志时,代码可能更清晰。

int height;
bool inputCorrect;

do
{
   printf("Height: ");
   height = GetInt();
   inputCorrect = (height > 1) && (height <= 23);
   if(!inputCorrect) {
       printf("Please fill in a number between 1-23!")
   }
} while(!inputCorrect);

使用有意义的名称,在略读代码时这将更具可读性。 while(!inputCorrect)是循环正在做的很好的总结。

相关问题