简体   繁体   English

基本的While循环优先级(C)

[英]Basic While Loop Precedence (C)

I'm new to coding and am learning C. I just had a question regarding while loops. 我是编码新手,正在学习C。我只是有一个关于while循环的问题。

#include <stdio.h>

int main(void) {
    int integer1, integer2, number, sum, largest, smallest;
    float average;

    integer1 = 0;
    number = 0;
    sum = 0;
    largest = integer1;
    smallest = integer1;

    while (integer1 != -1) {
        printf("Enter the number: ");
        scanf_s("%d", &integer1);
        number++;
        sum = sum + integer1;

        if (integer1 >= largest) {
            largest = integer1;
        }
        if (integer1 <= smallest) {
            smallest = integer1;
        }
    }

    average = (float) sum / number;

    printf("The number of user's input: %d.\n", number);
    printf("The sum of input numbers: %d.\n", sum);
    printf("The average of input numbers: %.2f.\n", average);
    printf("The largest number is: %d.\n", largest);
    printf("The smallest number is %d.\n", smallest);

    return 0;
}

The objective of the code I've written is to: 我编写的代码的目标是:

  1. Read integer values from the user. 从用户读取整数值。
  2. Terminate the while loop when the user enters '-1'. 当用户输入“ -1”时,终止while循环。
  3. Output the printf statements with their corresponding values. 输出printf语句及其相应的值。

Here's the problem: All of the integer variables that I've declared should NOT include the value of '-1; 这是问题所在:我声明的所有整数变量都不应包含'-1;值; inputted by the user. 由用户输入。 I assume that this has to do with an issue of precedence regarding the while loop, but I can't seem to pinpoint what it is. 我认为这与while循环的优先级问题有关,但我似乎无法查明它是什么。 Any help or insight is greatly appreciated. 任何帮助或见解将不胜感激。

Thank you! 谢谢!

Sometimes neither while nor do / while loop fit your needs, because the decision to exit the loop must be made in the middle of loop's body. 有时,既不while也不do / while循环满足您的需求,因为退出循环的决定必须以循环体的中间进行。

Reading values and deciding what to do after the read presents one of such situations. 读取值并确定读取后的操作会出现这种情况之一。 A common solution is to set up an infinite loop, and exit it from the middle on a break : 一个常见的解决方案是建立一个无限循环,并在中间break退出它:

for (;;) {
    printf("Enter the number: ");
    scanf_s("%d", &integer1);
    if (integer1 == -1) {
        break;
    }
    ... // The rest of your code
}

In order to achieve what you want you need to add one line. 为了实现您想要的,您需要添加一行。

 //use infinite loop
  while (1) {
        printf("Enter the number: ");
        scanf_s("%d", &integer1);
        //jump out of the loop because the loop has already started.
        //but the value was -1
        if (integer == -1) break;
        number++;
        sum = sum + integer1;

        if (integer1 >= largest) {
            largest = integer1;
        }
        if (integer1 <= smallest) {
            smallest = integer1;
        }
    }

只需在while循环之前添加scanf()语句即可。

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

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