donkey
donkey

Reputation: 513

why isn't fscanf() working?

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

int main() {
    int test, l , b, sqr, area, sqra, num;
    fscanf(stdin, "%d", &test);
    while(test--) {
        fscanf(stdin, "%d %d", &l, &b);    //input:
        area = l * b;                      //2
        sqr = sqrt(area);                  //2 2
        sqra = sqr * sqr;                  //7 9
        while(sqr) {
            if(!(area % sqra)) {
                num = area / sqra;
                --sqr;
                break;
            }
        } 
        fprintf(stdout, "%d\n", num);
    }
    return 0;
}

my code does not works when test >= 2. I think the problem is with fscanf. Can you explain why is that?

Upvotes: 1

Views: 550

Answers (3)

Tomer Arazy
Tomer Arazy

Reputation: 1823

I don't think it has to do anything with scanf, for example: if l=2 and b=3 then area=6, sqrt(area) is int so it's being rounded to 2, then sqra=4, area%sqra is then 6%4=2, so it never goes into the condition in the loop which creates an infinite loop.

Same goes to the 2nd input in your example : 7*9=63 => sqr=7 => sqra = 49 => area%sqra=14. Again, infinite loop.

Upvotes: 3

Dineshkumar
Dineshkumar

Reputation: 4245

[after declaring num] Your fscanf works fine:

    fscanf(stdin, "%d %d", &l, &b);
    printf("inp: %d %d\n",l,b);

Try printing the user input. it works. Your code logic is wrong so that only you are not getting expected result.

Upvotes: 1

Triclops200
Triclops200

Reputation: 833

You should really use scanf, not fscanf for this, and, also, where did you declare num at? I'm surprised it compiles at all. Also, the case where you have area is not divisible by sqra will have an infinite loop. (such as a rectangle with sides 3 and 7)

Upvotes: 1

Related Questions