c - 为什么 fscanf() 不工作?

标签 c scanf

#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;
}

我的代码在测试 >= 2 时不起作用。我认为问题出在 fscanf 上。你能解释一下这是为什么吗?

最佳答案

我认为它与 scanf 没有任何关系,例如:如果 l=2 和 b=3,则 area=6,sqrt(area) 是 int,因此它被四舍五入为 2,则 sqra=4, area%sqra 是 6%4=2,所以它永远不会进入循环中创建无限循环的条件。

您示例中的第二个输入也是如此:7*9=63 => sqr=7 => sqra = 49 => area%sqra=14。同样,无限循环。

关于c - 为什么 fscanf() 不工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16902986/

相关文章:

c - 提高多线程程序的速度

c - 检测到堆损坏 - 使用字符串实现合并排序

c - 为什么下面的程序会发生溢出?

c - 为什么 scanf 会让我的 switch 语句崩溃?

c - 在循环中使用 fscanf() 的问题

C、使用动态内存分配的矩阵转置乘法

c - For循环在C中崩溃

c - scanf 格式的空白字符问题

C:将二维数组分配给另一个数组

有人可以解释这种行为吗?