C++浮点数操作
十进制数的数值实现是一个浮点数。在C++编程语言中,浮点数的大小为32位。并且有一些浮点数操作函数可以处理浮点数。这里我们介绍了一些浮点数操作函数。
fmod()
作用于浮点数的fmod()函数将返回该方法传递参数的除法余数。
示例
#include <iostream> #include <cmath> using namespace std; int main() { float a, b, rem; a = 23.4; b = 4.1; rem = fmod(a,b); cout<<"The value of fmod( "<<a<<" , "<<b<<" ) = "<<rem; }
输出
The value of fmod( 23.4 , 4.1 ) = 2.9
remainder()
remainder()函数的功能与fmod函数相同。并返回两个值之间除法的余数。此方法返回数值方面尽可能小的余数。也可能是负数。
示例
#include <iostream> #include <cmath> using namespace std; int main() { float a, b, rem; a = 23.4; b = 4.1; rem = remainder(a,b); cout<<"The value of remainder( "<<a<<" , "<<b<<" ) = "<<rem; }
输出
The value of remainder( 23.4 , 4.1 ) = -1.2
remquo()
此方法返回两个传递值的商和余数,它还需要一个变量的引用,该变量将具有商的值。因此,此方法将返回与remainder函数相同的余数和商的引用。
示例
#include <iostream> #include <cmath> using namespace std; int main() { float a, b, rem; int quo; a = 23.4; b = 4.1; rem = remquo(a,b,&quo); cout<<a<<" and "<<b<<" passed to the remquo() function gives the following output\n"; cout<<"The remainder is "<<rem<<endl; cout<<"The quotient is "<<quo; }
输出
23.4 and 4.1 pass to the the remque() function gives the following output The reminder is -1.2 The quotient is 6
copysign()
C语言的copysign函数返回一个具有其他变量符号的变量。返回的变量具有第一个变量的幅度和第二个变量的符号。
示例
#include <iostream> #include <cmath> using namespace std; int main(){ double a, b; a = 9.6; b = -3.5; cout<<"copysign function with inputs "<<a<<" and "<<b<<" is "<<copysign(a,b); }
输出
Copysign function with inputs 9.6 and -3.5 is -9.6
fmin()
顾名思义,fmin函数返回函数两个参数中的最小值。返回类型为浮点数。
示例
#include <iostream> #include <cmath> using namespace std; int main(){ double a, b; a = 43.5; b = 21.2; cout << "The smallest of "<<a<<" and "<<b<<" is "; cout << fmin(a,b)<<endl; }
输出
The smallest of 43.5 and 21.2 is 21.2
fmax()
fmax函数是一个C编程函数,它返回参数中两个数字中最大的数字。
示例
#include <iostream> #include <cmath> using namespace std; int main(){ double a, b; a = 43.5; b = 21.2; cout << "The largest of "<<a<<" and "<<b<<" is "; cout << fmax(a,b)<<endl; }
输出
The largest of 43.5 and 21.2 is 43.5
fdim()
C编程语言的fdim()函数返回作为函数参数发送的两个数字的绝对差。
示例
#include <iostream> #include <cmath> using namespace std; int main(){ double a, b; a = 43.5; b = 21.2; cout << "The absolute difference of "<<a<<" and "<<b<<" is"; cout << fdim(a,b)<<endl; }
输出
The absolute difference of 43.5 and 21.2 is 22.3
fma()
C语言的fma()函数返回给定参数的乘积。该函数返回一个浮点数,并接受三个浮点参数。
示例
#include <iostream> #include <cmath> using namespace std; int main(){ double a, b, c; a = 3.5; b = 2.4; c = 7.2; cout << "The multiplication of "<<a<<" , "<<b<<" and "<<c<<" is "; cout << fma(a,b,c)<<endl; }
输出
The multiplication of 3.5 , 2.4 and 7.2 is 15.6
这些都是在浮点数上操作的所有函数。这些函数在cmath库中定义。
广告