C ++中的copysign()函數(shù)接受兩個參數(shù),并返回一個值,該值具有第一個參數(shù)的大小和第二個參數(shù)的符號。
該函數(shù)在<cmath>頭文件中定義。
double copysign(double x, double y); float copysign(float x, float y); long double copysign(long double x, long double y); Promoted copysign(Type1 x, Type2 y); // Additional overloads for arithmetic types
從C ++ 11開始,如果傳遞給copysign()的參數(shù)為long double,則返回類型Promoted為long double。如果不是,則返回類型Promoted為double。
x:帶有結(jié)果值大小的值。
y:帶有結(jié)果值符號的值。
copysign()函數(shù)返回將參數(shù)y的符號賦予x的數(shù)據(jù)。
#include <iostream> #include <cmath> using namespace std; int main() { double x = 34.15, y = -13.0, result; result = copysign(x, y); cout << "copysign(" << x << "," << y << ") = " << result << endl; return 0; }
運(yùn)行該程序時,輸出為:
copysign(34.15,-13) = -34.15
#include <iostream> #include <cmath> using namespace std; int main() { double x = 34.15, result; int y = -54; result = copysign(x, y); cout << "copysign(" << x << "," << y << ") = " << result << endl; return 0; }
運(yùn)行該程序時,輸出為:
copysign(34.15,-54) = -34.15