如何在C中找出一个双数是否有小数点后的任何数字
How to find out in C whether a double number has any digits after decimal point
我在用 C 语言实现给定算法时偶然发现了一个问题:
int getNumberOfAllFactors(int number) {
int counter = 0;
double sqrt_num = sqrt(number);
for (int i = 1; i <= sqrt_num; i++) {
if ( number % i == 0) {
counter = counter + 2;
}
}
if (number == sqrt_num * sqrt_num)
counter--;
return counter;
}
– 第二个条件的原因 – 是为了对完全平方进行校正(即 36 = 6 * 6),但是它不会避免像这样的情况(误报):
sqrt(91) = 18.027756377319946
18.027756377319946 * 18.027756377319946 = 91.0
所以我的问题是:如何避免它以及在 C 语言中找出双数是否有小数点后任何数字的最佳方法是什么?我应该将平方根值从双精度转换为整数吗?
对于你的情况,你可以这样测试:
if (sqrt_num == (int)sqrt_num)
您可能应该使用 modf()
系列函数:
#include <math.h>
double modf(double value, double *iptr);
The modf
functions break the argument value into integral and fractional parts, each of
which has the same type and sign as the argument. They store the integral part (in
floating-point format) in the object pointed to by iptr
.
这比尝试使用直接转换为 int
更可靠,因为 int
通常是 32 位数字,而 double
通常可以存储更大的整数值(最多 53 位)所以你可以 运行 陷入不必要的错误。如果您决定必须使用到 int
的转换并且正在使用 double
值,至少使用 long long
进行转换而不是 int
.
(该家族的其他成员是处理 float
的 modff()
和处理 long double
的 modfl()
。)
我在用 C 语言实现给定算法时偶然发现了一个问题:
int getNumberOfAllFactors(int number) {
int counter = 0;
double sqrt_num = sqrt(number);
for (int i = 1; i <= sqrt_num; i++) {
if ( number % i == 0) {
counter = counter + 2;
}
}
if (number == sqrt_num * sqrt_num)
counter--;
return counter;
}
– 第二个条件的原因 – 是为了对完全平方进行校正(即 36 = 6 * 6),但是它不会避免像这样的情况(误报):
sqrt(91) = 18.027756377319946
18.027756377319946 * 18.027756377319946 = 91.0
所以我的问题是:如何避免它以及在 C 语言中找出双数是否有小数点后任何数字的最佳方法是什么?我应该将平方根值从双精度转换为整数吗?
对于你的情况,你可以这样测试:
if (sqrt_num == (int)sqrt_num)
您可能应该使用 modf()
系列函数:
#include <math.h> double modf(double value, double *iptr);
The
modf
functions break the argument value into integral and fractional parts, each of which has the same type and sign as the argument. They store the integral part (in floating-point format) in the object pointed to byiptr
.
这比尝试使用直接转换为 int
更可靠,因为 int
通常是 32 位数字,而 double
通常可以存储更大的整数值(最多 53 位)所以你可以 运行 陷入不必要的错误。如果您决定必须使用到 int
的转换并且正在使用 double
值,至少使用 long long
进行转换而不是 int
.
(该家族的其他成员是处理 float
的 modff()
和处理 long double
的 modfl()
。)