【问题标题】:C program that displays the max of entered %2==0 numbers until you enter a number %2!=0 && %7==0显示输入的最大 %2==0 个数字的 C 程序,直到您输入一个数字 %2!=0 && %7==0
【发布时间】:2014-11-12 13:36:41
【问题描述】:

这个程序必须接受用户的输入(一个数字)并重复,直到输入一个可被 7 整除的奇数。然后它必须打印输入的最大偶数。

尝试了两种方法:嵌套和双 while 循环。我遇到的问题是,在我输入一个可被 7 整除但不是奇数(比如 28)的数字后,如果我输入一个奇数(比如 3),程序会打印最大值。它应该让我再次输入数字,直到我输入一个可被 7 整除的奇数(比如说 21)。

嵌套代码:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int x, max = 0, suma = 0, impar, par = 0;

    while (x % 7 != 0)
    { 
        while(x % 2 == 0 || x % 2 != 0)
        {
            printf("Introduceti un numar:\n");           //Enter a number
            scanf("%d", &x);
            if (x % 2 == 0)
                if (x > max)
                    max = x;
        }

        printf("Introduceti un numar:\n");            //Enter a number
        scanf("%d", &x);
        if (x % 2== 0)
            if (x > max)
                max = x;
        if (x % 2 != 0)
            break;
    }  
    printf("Maximul numerelor pare introduse este: %d",max);  
}

为什么我们要这样做,我在 C 中找不到有关嵌套 while 循环的信息。编译器首先测试内部循环?谁能用一个简单的例子解释一下?

【问题讨论】:

  • 根据答案修改,现在可以了。

标签: c loops numbers nested


【解决方案1】:

您的代码具有未定义的行为,因为您有一个依赖于xwhile 您分配x 一个值之前。如果您要输入来自用户的值,则无法在读取该值之前测试该值。您的 while 循环没有正确表达您想要做什么。

可以使用无限循环来完成,只需break在必要时退出。

不,循环(当然)不是由内而外评估的。它们按程序顺序进行评估。

【讨论】:

  • @Stack_token:您可能还想用scanf(" %d", &amp;x); 替换scanf("%d", &amp;x); 注意空格。这将使 scanf 跳过可能在输入缓冲区中的前导空格(包括 EOL 字符)
猜你喜欢
  • 1970-01-01
  • 2020-07-17
  • 1970-01-01
  • 1970-01-01
  • 2012-12-08
  • 2013-07-15
  • 1970-01-01
  • 1970-01-01
  • 2019-08-02
相关资源
最近更新 更多