【发布时间】:2013-06-03 18:03:57
【问题描述】:
#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;
}
我的代码在 test >= 2 时不起作用。我认为问题出在 fscanf 上。你能解释一下为什么会这样吗?
【问题讨论】:
-
您在哪里以及如何声明
num?另外,如果area的平方根小于一,那么sqr中的结果将被截断为零(这意味着循环不会运行,num很可能会包含一个随机值)。 -
为了帮助您找到问题所在,我建议您在调试器中逐行运行程序,同时检查所有计算的结果。
-
您应该提供一些示例输入。
-
你能解释一下为什么 fscanf 不工作吗?
-
由于您不测试来自
fscanf()的返回值,因此您不知道fscanf()是否有效。您必须注意scanf()系列函数(实际上是大多数输入函数)的返回值。if (fscanf(stdin, "%d", &test) != 1) ... process error...和if (fscanf(stdin, "%d %d", &l, &b) != 2) ... process error....