我正在尝试通过 UVA 在线法官解决此问题:http://uva.onlinejudge.org/index.php?option=onlinejudge&page=show_problem&problem=2456
问题陈述
A square number is an integer number whose square root is also an integer. For example 1, 4, 81 are some square numbers. Given two numbers a and b you will have to find out how many square numbers are there between a and b (inclusive).
我尝试过的代码:
#include <stdio.h>
int main()
{
long long int num1, num2, count = 0;
int t, i;
while (1)
{
count = 0;
scanf("%lld%lld", &num1, &num2);
if (num1 == 0 && num2 == 0)
break;
for (; num1 * num1 <= num2; num1 ++)
count++;
printf("%lld\n", count);
}
return 0;
}
法官的回应
在线提交过程告诉我,我的代码产生了错误的答案,但我无法弄清楚原因。谁能看到我的代码中的错误吗?
最佳答案
您遇到的第一个问题是您误解了问题陈述。
您不应该计算数字的平方
,而应该计算平方根
。
如果平方根
是一个整数,那么它才是一个平方数
。
获得正确计数的另一种方法实际上是计算平方
,但不是计算从a
到b
的数字,而是根据a 的平方根
到b 的平方根
。
关于c - 代码哪里错了?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26937790/