显示在C中使用while循环输入的最大数字?

时间:2015-10-22 19:14:21

标签: c

我正在创建一个小程序,它使用while循环来要求用户输入大于0的数字。当程序运行时,只有循环工作,但我没有看到最大的数字。这是代码:

#include <stdio.h>

int main(void) {

        int num1;
        int biggestValue = 0;

        printf("Enter a number: ");
        scanf("%d", &num1);

        while (num1 != 0) {

                printf("Enter a number (0 to exit): ");
                scanf("%d", &num1);

                biggestValue = num1;

                if (biggestValue > num1) {

                        printf("Biggest value is: %d \n", biggestValue);
                }
        }

}

4 个答案:

答案 0 :(得分:1)

使用此代码

#include <stdio.h>

int main(void)
{

    int num1;
    int biggestValue = 0;

    printf("Enter a number: ");
    scanf("%d", &num1);

    while (num1 != 0)
    {

        if (biggestValue < num1)
        {
            biggestValue = num1;
        }
        printf("Enter a number (0 to exit): ");
        scanf("%d", &num1);
    }
    printf("Biggest value is: %d \n", biggestValue);
}

说明:

  1. 首先,您需要检查输入的号码num1是否大于biggestValue
  2. 如果num1大于biggestValue,则biggestValue=num1
  3. 其他biggestValue保持不变。
  4. 外部循环打印biggestValue

答案 1 :(得分:1)

在显示biggestValue之前不要设置 // biggestValue = num1; if (num1 > biggestValue) { biggestValue = num1; // move here printf("Biggest value is: %d \n", biggestValue); }

更改比较订单@Zaman

#include <limits.h>
#include <stdio.h>
int main(void) {
  int biggestValue = INT_MIN;
  const char *prompt = "Enter a number: ";
  for (;;) {
    fputs(prompt, stdout);
    int num1;
    if (scanf("%d", &num1) != 1) break;
    if (num1 > biggestValue) {
      biggestValue = num1;
    }
    prompt = "Enter a number (or 'q' to exit): ";
  }
  printf("Biggest value is: %d \n", biggestValue);
  return 0;
}

示例完整解决方案:

\((.+?)(?<!\\)\)

答案 2 :(得分:0)

由于您正在设置biggestValue = num1;,然后立即检查是否biggestValue > num1biggestValue永远不会大于num1。他们永远是平等的。

我认为你想要的是:

if (biggestValue < num1) {
    biggestValue = num1;
}

然后在while循环之外放置:

printf("Biggest value is: %d \n", biggestValue);

答案 3 :(得分:0)

打印应该在while循环之后,并且在比较之前不要写biggestValue = num1;

#include <stdio.h>

int main(void)
{
    int num1;

    int biggestValue = 0;

    while (num1 != 0)
    {
        printf("Enter a number (0 to exit): ");

        scanf("%d", &num1);

        if (biggestValue < num1)
        {
            biggestValue = num1;
        }
    }
    printf("Biggest value is: %d \n", biggestValue);
}