使用多个scanf打印最大偶数

时间:2017-10-31 23:08:30

标签: c arrays loops if-statement scanf

我想获得最大偶数的输出。但是当我输入1 2 3(3次调用scanf)时,输出为4

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

int main() {
    int ary[100];
    int x, y = 0;
    int amount;
    scanf("%d", &amount);
    fflush(stdin);
    for (x = 1; x <= amount; x++) {
        scanf("%d", &ary[x]);
        if (ary[x] % 2 == 0) {
            if (ary[0] < ary[x]) {
                ary[0] = ary[x];
            }
        }
    }
    printf("%d", ary[0]);

    getchar();
    return 0;
}

3 个答案:

答案 0 :(得分:2)

在循环初始化ary[0]之前,例如以下方式(在程序中使用ary[0]的未初始化值)

ary[0] = 1;

然后替换这些if语句

    if(ary[x]%2==0)
    {
        if(ary[0]<ary[x])

if( ary[x]%2==0 && ( x == 1 || ary[0]<ary[x] ) )

最后写

if ( ary[0] != 1 ) printf("%d",ary[0]);

考虑到这个电话

fflush(stdin);

有未定义的行为,应该删除。

实际上没有必要声明一个数组。如果没有数组,程序可能看起来像

#include <stdio.h>

int main( void )
{
    unsigned int n;
    int max_even = 1;

    printf("How many numbers are you going to enter: ");
    scanf("%u", &n);

    int x;

    for (unsigned int i = 0; i < n && scanf( "%d", &x ) == 1; i++)
    {
        if ((x % 2) == 0 && (max_even == 1 || max_even < x))
        {
            max_even = x;
        }
    }

    if (max_even != 1)
    {
        printf("maximum entered even number is %d\n", max_even);
    }
    else
    {
        puts("None even number was enetered");
    }

    return 0;
}

它的输出可能看起来像

How many numbers are you going to enter: 10
0 1 2 3 4 5 6 7 8 9
maximum entered even number is 8

答案 1 :(得分:0)

您的代码不起作用,因为ary[0]在您第一次将其值与读取的值进行比较时尚未初始化,而且对于其他比较可能不均匀。

你应该用一个指示器告诉你是否看到了偶数值。

这是一个解决方案:

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

int main(void) {
    int has_even = 0, max_even = 0, value, amount, x;

    if (scanf("%d", &amount) != 1)
        return 1;
    for (x = 0; x < amount; x++) {
        if (scanf("%d", &value) != 1)
            break;
        if (!has_even || value > max) {
            max_even = value;
            has_even = 1;
        }
    }
    if (has_even)
        printf("%d\n", max_even);
    else
        printf("no even value\n");

    getchar();
    return 0;
}

答案 2 :(得分:0)

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

int main() {
 int ary[100];
 int ary[0 = 0;
 int x, y = 0;
 int amount;
 scanf("%d", &amount);
 fflush(stdin);
 for (x = 1; x <= amount; x++) {
    scanf("%d", &ary[x]);
    if (ary[x] % 2 == 0) {
        if (ary[0] < ary[x]) {
            ary[0] = ary[x];
        }
    }
}
printf("%d", ary[0]);

getchar();
return 0;

}