2

I've been trying to figure out what was wrong with my code for almost hours now, but I cannot seem to find it. My code was compiling, which tells me there are no errors violating the compiler, but my program doesn't work the way I want it to.

My code is:

#include <stdio.h>
#define MAXNUM 3
#define MAXLEN 9

int main ()
{
        char input[MAXNUM][MAXLEN];
        int count;
        int a = 0;
    for ( count = 0; (count + 1) < MAXNUM; count++ ) { 
    printf ( "Enter number: (12XXXXXXX): " );
        if ((fgets ( input[count], sizeof(input), stdin )) != 0 ) {
            a = atoi (input[count]);
            if ((( a / 10000000 ) >= 13 ) || (( a / 10000000 ) <= 11 )) {
            //error message
            }
        } else {
            //error message
        }
    } 
    return 0;

}

The program was supposed to be taking three inputs, but it takes four, and then terminates fatally. Its other functions are working correctly (dealing with wrong inputs, etc), the only problems seems to be the number of times it should ask an input from the user. I assumed that the mistake is in my for loop condition and I've been trying to figure it out but to no avail. Can anyone point it out?

*OKAY I'VE FIGURED IT OUT. It's in the for loop condition: * (count + 1) <= MAXNUM

4

1 回答 1

0

for()循环迭代 1 到经常。所以而不是

for ( count = 0; (count + 1) < MAXNUM; count++ ) {

用。。。来代替

for ( count = 0; count < MAXNUM; count++ ) {

我注意到 OP 用自己的解决方案编辑了这个问题:

(count + 1) <= MAXNUM;

这几乎是等价的。选择编译器在处理count + 1溢出时会有所不同。推荐惯用的count < MAXNUM解决方案。

于 2013-09-06T01:33:38.187 回答