[英]How to find out in C whether a double number has any digits after decimal point
I stumbled on one issue while I was implementing in C the given algorithm: 当我在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;
}
– the reason for second condition – is to make a correction for perfect squares (ie 36 = 6 * 6), however it does not avoid situations (false positives) like this one: - 第二个条件的原因 - 是对正方形进行校正(即36 = 6 * 6),但它不能避免像这样的情况(误报):
sqrt(91) = 18.027756377319946
18.027756377319946 * 18.027756377319946 = 91.0
So my questions are: how to avoid it and what is the best way in C language to figure out whether a double number has any digits after decimal point? 所以我的问题是:如何避免它以及C语言中最好的方法是确定双数是否在小数点后有任何数字? Should I cast square root values from double to integers?
我应该将平方根值从double转换为整数吗?
在您的情况下,您可以像这样测试它:
if (sqrt_num == (int)sqrt_num)
You should probably use the modf()
family of functions: 您应该使用
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.modf
函数将参数值分解为整数和小数部分,每个部分具有与参数相同的类型和符号。 They store the integral part (in floating-point format) in the object pointed to byiptr
.它们将整数部分(浮点格式)存储在
iptr
指向的对象中。
This is more reliable than trying to use direct conversions to int
because an int
is typically a 32-bit number and a double
can usually store far larger integer values (up to 53 bits worth) so you can run into errors unnecessarily. 这比尝试直接转换为
int
更可靠,因为int
通常是32位数,而double
通常可以存储更大的整数值(最多53位),因此您可能会不必要地遇到错误。 If you decide you must use a conversion to int
and are working with double
values, at least use long long
for the conversion rather than int
. 如果您决定必须使用转换为
int
并使用double
值,则至少使用long long
进行转换而不是int
。
(The other members of the family are modff()
which handles float
and modfl()
which handles long double
.) (该系列的其他成员是
modff()
,它处理float
和modfl()
,它处理long double
。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.