【发布时间】: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 循环的信息。编译器首先测试内部循环?谁能用一个简单的例子解释一下?
【问题讨论】:
-
根据答案修改,现在可以了。