简体   繁体   English

如何在C语言的早期结束循环?

[英]How to end a loop early in C?

I have a basic C program that produces a number and the user has to guess it (yup, you've already called it: homework). 我有一个基本的C程序产生一个数字,用户必须猜测它(是的,你已经称它为:家庭作业)。 I am able to get pretty much all of it so I am kinda proud, but I open to any errors I have made of course I am still learning. 我能够得到相当多的所有这些,所以我有点自豪,但我接受我所做的任何错误,当然我还在学习。 My main two questions are 我的主要两个问题是

  1. How can I end this program early once the user has selected the correct number, before it has reached the #10 of tries? 一旦用户选择了正确的号码,在达到尝试次数#10之前,我该如何提前结束该程序? And
  2. Any obvious errors a guru can see that I'm not with my code? 大师可以看到任何明显的错误,我没有使用我的代码?

I am trying to program as best as I can :) 我尽力编程尽我所能:)

int main(void)
{
    int x = 10;
    int i = 0;
    int target, guess;
    int numGuess = 0;

    /*create a random number*/
    //create random function
    srand(time(NULL));//this creates new number based on time which changes every second :)
    target = rand() % 99; //create a random number using the rand() function, from 0 -99



    do{
        //increase the loop until it meets the x variable
        i++;
        numGuess++;
        //allow user to input a number for guess
        scanf("%d", &guess);
        if (guess == target)
        {
            printf("You win! \n\n");

        }
        else if (guess > target)
        {
            printf("You are too high. Guess a number:\n\n");
        }
        else if (guess < target)
        {
            printf("You are too low. Guess a number:\n\n");
        }

    }while(i < x);
        printf("You lose, the number was %d. \n", target);

    printf("Number of tries %d\n", numGuess);
    printf("Enter any key to exit...");
    getchar();
    getchar();

    return 0;
}

Use the break statement to hop out of a loop: In this case though that may not be what you want since once you break out of the loop you will instantly see the "you lose" message. 使用break语句跳出循环:在这种情况下,虽然这可能不是你想要的,因为一旦你突破循环,你将立即看到“你输了”的消息。 You may need to restructure your program to account for this. 您可能需要重新构建程序以解决此问题。

Try something like this: 尝试这样的事情:

int main(void)
{
    int x = 10;
    int i = 0;
    int target, guess;
    int numGuess = 0;

    /*create a random number*/
    //create random function
    srand(time(NULL));//this creates new number based on time which changes every second :)
    target = rand() % 99; //create a random number using the rand() function, from 0 -99

    do {
        //increase the loop until it meets the x variable
        i++;
        numGuess++;
        //allow user to input a number for guess
        scanf("%d", &guess);
        if (guess == target)
        {
            printf("You win! \n\n");
            break;
        }
        else if (guess > target)
        {
            printf("You are too high. Guess a number:\n\n");
        }
        else if (guess < target)
        {
            printf("You are too low. Guess a number:\n\n");
        }

    }while(i < x);

    if (guess != target) {
        printf("You lose, the number was %d. \n", target);
    }

    printf("Number of tries %d\n", numGuess);
    printf("Enter any key to exit...");
    getchar();
    getchar();

    return 0;
}

You are looking for the break command. 您正在寻找break命令。

for (int i = 0; i < 10; i++) {
    if(i == 5)
       break;
}

This resource looks like it would be very helpful to you. 这个资源看起来对你很有帮助。

As a side note: your "You lose" text will always be displayed no matter what. 作为旁注:无论如何,您的“遗失”文本将始终显示。 You may want to evaluate that inside the do{ } loop. 您可能想要在do {}循环内进行评估。


Always one step ahead of me with the posts/edits on this answer Andrew Hare! 这个答案安德鲁·黑尔的帖子/编辑总是领先我一步!

Why not set the while condition to the user's guess? 为什么不将while条件设置为用户的猜测? Something like: 就像是:

 ...}while(i < x || guess !== target);

Here are three possibilities. 这有三种可能性。 Read about them!!! 了解他们! (goto considered harmful) (转到认为有害)

 if (guess == target)
 {
     printf("You win! \n\n");
     break;
 }

 if (guess == target)
 {
     printf("You win! \n\n");
     goto end;
 }


 if (guess == target)
 {
     printf("You win! \n\n");
     i=n;
 }

I do not see any "obvious errors" that previous posters did not mention, other than the fact that, with the break, you no longer need both "i" and "numGuess" as they would always have the same value. 我没有看到之前的海报没有提及的任何“明显的错误”,除了这个事实,在休息时,你不再需要“i”和“numGuess”,因为它们总是具有相同的值。 Just use numGuess instead of "i" in the while's condition. 只需在while的条件下使用numGuess而不是“i”。

But I would like to highly recommend you to make your code more readable - the best time to get into the habit of good coding style is now, before you acquire and solidify bad habits. 但我强烈建议你让你的代码更具可读性 - 现在,在你获得并巩固坏习惯之前,养成良好编码风格习惯的最佳时机。

  • Always use self-describing identifyers (variable/function names). 始终使用自描述标识符(变量/函数名称)。 Eg your "x" should really be called "maxGuesses". 例如你的“x”应该被称为“maxGuesses”。

  • Don't skimp on white space. 不要在白色空间上吝啬。 Eg "}while(i < x);" 例如“} while(i <x);” should be "} while (i < x);" 应该是“} while(i <x);”

  • You seem to have already gotten into the habit of not skimping on comments - good!!! 你似乎已经养成了不吝啬评论的习惯 - 好!!!

    Just remember that the comments should always describe the purpose behind what the code does instead of the mechanics of how it does it unless the mechanics is so tricky and clever that it also needs explanation. 请记住,评论应始终描述代码所处的目的,而不是它如何做到的机制,除非机制是如此棘手和聪明,它还需要解释。

The reason that this is important is two-fold: 这很重要的原因是双重的:

  • 80-90% of development time/efforts are usually spent on maintaining existing code, your own or someone else's. 80-90%的开发时间/工作通常用于维护现有代码,您自己或其他人的代码。 That task is VASTLY easier with well documented and easily readable code. 通过记录良好且易于阅读的代码,该任务变得更加容易。 (you have no idea how much brain damage someone can sustain from reading unfamiliar code at 2am during production problem just because the bozo who wrote it didn't indent the code consistently). (你不知道有人因为在制作过程中凌晨2点阅读不熟悉的代码而导致的脑损伤是多少,因为编写它的bozo没有一致地缩进代码)。

  • Having well documented and readable code makes it easier for you to write it, since it clarifies your own thoughts and discourages stupid typo-originated bugs ("oups, i meant to use x instead of y"). 有良好的文档和可读代码使您更容易编写它,因为它澄清了您自己的想法,并阻止了愚蠢的错字来源的错误(“oups,我的意思是使用x而不是y”)。

In the case of your program the best way to achieve this is probably to call 对于您的程序,实现此目的的最佳方法可能是调用

void exit(int status); void exit(int status);

(include stdlib.h ) (包括stdlib.h)

after printing "You Win" 打印后“You Win”

In general you can use the keyword "break" to exit a loop at any time. 通常,您可以使用关键字“break”随时退出循环。 This does not have the desired effect in your case as it would go on to print "you lose ...." . 这对你的情况没有预期的效果,因为它会继续打印“你输了......”。 If you want to use "break" you would have to put an "if" statement around the "you lose ..." bit and check whether the user has not in fact won. 如果你想使用“break”,你必须在“you lose ...”位置放一个“if”语句并检查用户是否实际上没赢。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM