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庫中定義。

更新於:2019年9月19日

1K+瀏覽量

開啟你的職業生涯

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.