简体   繁体   English

为什么fscanf()不起作用?

[英]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. 当test> = 2时,我的代码不起作用。我认为问题出在fscanf。 Can you explain why is that? 你能解释为什么吗?

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. 我认为它与scanf无关,例如:如果l = 2和b = 3,则area = 6,sqrt(area)是int,因此将其舍入为2,然后sqra = 4,area%sqra则为6%4 = 2,因此它永远不会进入创建无限循环的循环条件。

Same goes to the 2nd input in your example : 7*9=63 => sqr=7 => sqra = 49 => area%sqra=14. 在您的示例中,第二个输入也是如此:7 * 9 = 63 => sqr = 7 => sqra = 49 => area%sqra = 14。 Again, infinite loop. 同样,无限循环。

You should really use scanf, not fscanf for this, and, also, where did you declare num at? 您应该真正使用scanf,而不是fscanf,而且,您在哪里声明num? I'm surprised it compiles at all. 我很惊讶它完全可以编译。 Also, the case where you have area is not divisible by sqra will have an infinite loop. 同样,如果您的面积不能被sqra整除,则会出现无限循环。 (such as a rectangle with sides 3 and 7) (例如边长为3和7的矩形)

[after declaring num] Your fscanf works fine: [声明num之后]您的fscanf正常工作:

    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. 您的代码逻辑是错误的,因此只有您无法获得预期的结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM