[英]What does *1.0 do in this code?
Here is a code for checking if a number is prime or not : 这是一个用于检查数字是否为素数的代码:
bool IsPrime(int num)
{
if(num<=1)
return false;
if(num==2)
return true;
if(num%2==0)
return false;
int sRoot = sqrt(num*1.0);
for(int i=3; i<=sRoot; i+=2)
{
if(num%i==0)
return false;
}
return true;
}
What does the expression " num*1.0 " mean ? 表达“num * 1.0”是什么意思?
Multiplying by 1.0
forces the num
into a double
. 乘以
1.0
num
强制为double
。 You can do the same with an explicit cast. 您可以使用显式强制转换来执行相同操作。
它正在执行num x 1.0,所以如果num是5,则它是5 x 1.0,sqrt()方法需要double作为其参数,并且需要5.0
In num*1.0
, num
is promoted to double
first, so the result is a double
and then pass to double sqrt(double)
. 在
num*1.0
, num
被提升为double
,因此结果是double
,然后传递给double sqrt(double)
。 Otherwise, you may need to use sqrt(static_cast<double>(num))
. 否则,您可能需要使用
sqrt(static_cast<double>(num))
。
Generally, you don't need the cast because there is an implicit cast from int
to double
. 通常,您不需要强制转换,因为存在从
int
到double
的隐式转换。 Refer to here . 请参阅此处 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.