-1

这是一个从输入文件中找出最大偶数及其出现次数并将其输出到输出文件的程序。我的输出有问题,似乎有一个额外的迭代把事情搞砸了。

int main(int argc, char const *argv[])
{
    int n, num, i, even, count;

    FILE * fptr;
    FILE * fptro;

    fptr =fopen("maximpar.in", "r");
    fptro=fopen("maximpar.out", "w");

   /*scanning the first line from the file to get n for for()*/

    fscanf(fptr, "%d", &n); 

    count = 0;
    even = INT_MIN;
    for(i = 0; i < n; i++)
{
    fscanf(fptr, "%d", &num);

    if( (num % 2 == 0 && num > even) || (even == num) ) 

    /*checking  for largest even number, 
    not sure about the ..||(even == num) part of the condition*/

    {
        even = num;
        count++;
    }

}

    fprintf(fptro, "%d %d", even, count);


    fclose(fptr);
    fclose(fptro);

    return 0;
}

输入文件

 6
 9 6 9 8 9 8

输出文件

8 3 

为什么输出文件不是这样?我不明白

8 2
4

3 回答 3

1

附上条件

   if(  ( ...&&...) ||(....) )
于 2018-12-24T19:46:56.663 回答
1

每当您获得更大的新数字时,您都需要重置您的计数。

我没有对此进行测试,但它应该可以工作:

cate = 0;
par = INT_MIN;

for (i = 0; i < n; i++) {
    fscanf(fptr, "%d", &b);

    // skip odd numbers
    if ((b % 2) != 0)
        continue;

    // get new larger number
    if (b > par) {
        par = b;
        cate = 1;
        continue;
    }

    // increment count on existing largest number
    if (b == par)
        ++cate;
}

更新:

我不明白为什么要明确跳过迭代而不是只挑选重要的迭代?有什么优势吗?

是的,这是更好的风格。它允许简单的单级缩进if语句,可以有自己的注释。

它避免了杂乱的化合物if或三层if/else阶梯。

IMO,这是一个普遍的误解[特别是在初级 C 程序员中],一个复杂的if执行速度会比几个简单的执行得更快[或者在某种程度上“更好”]。

第一个if可以被认为是“跳过此迭代”测试。在这里,只有一个。但是,对于更复杂的代码,可能有几个。

可以一次处理多个条件转义ifif (c1 || c2 || c2 || ... || c10) continue;但很快就会变得混乱。

在这里,对于正确缩进的if/else梯形逻辑,我们需要:

if (cond1)
    do_stuff1;
else
    if (cond2)
        do_stuff2;
    else
        if (cond3)
            do_stuff3;

如果我们不在循环中,这里有一个“技巧”来避免if/else梯形逻辑,通过使用do { ... } while (0);

do {
    if (cond1) {
        do_stuff1;
        break;
    }

    if (cond2) {
        do_stuff2;
        break;
    }

    if (cond3) {
        do_stuff3;
        break;
    }
} while (0);
于 2018-12-24T20:07:43.570 回答
0

The answer is because count was incremented from 0 to 1 when b = 6. 2 iterations later, b = 8 and now count = 2, and 2 iterations after that, b = 8 and count = 3.

I also recommend you nest your if statement in parentheses for readability. Commenting would help too :) I'm a stats guy, and I have no idea what you are doing based on your variables' names.

You need to reset your counter inside the if block if b > par.

Like:

if( num % 2 == 0 && num >= even) {

if (num > even){ 

    even = num; 
    count = 1; 

} else { 

    count++; 

}

}

Thanks.

JK

于 2018-12-24T19:56:47.043 回答