C ++中的restder()函數(shù)計(jì)算分子/分母的浮點(diǎn)余數(shù)(四舍五入到最接近的值)。
remainder (x, y) = x - rquote * y
其中,rquote是x/y的結(jié)果,四舍五入到最接近的整數(shù)值(一半情況下四舍五入到偶數(shù))。
double remainder(double x, double y); float remainder(float x, float y); long double remainder(long double x, long double y); double remainder(Type1 x, Type2 y); // Additional overloads for other combinations of arithmetic types
restder()函數(shù)接受兩個(gè)參數(shù),并返回double,float或long double類(lèi)型的值。
此函數(shù)在<cmath>頭文件中定義。
x -分子的值。
y -分母的值。
restder()函數(shù)返回x/y的浮點(diǎn)余數(shù)(四舍五入到最接近的值)。
如果分母y為零,則remainder()返回NaN(不是數(shù)字)。
#include <iostream> #include <cmath> using namespace std; int main() { double x = 7.5, y = 2.1; double result = remainder(x, y); cout << "余數(shù) " << x << "/" << y << " = " << result << endl; x = -17.50, y=2.0; result = remainder(x, y); cout << "余數(shù) " << x << "/" << y << " = " << result << endl; y=0; result = remainder(x, y); cout << "余數(shù) " << x << "/" << y << " = " << result << endl; return 0; }
運(yùn)行該程序時(shí),輸出為:
余數(shù) 7.5/2.1 = -0.9 余數(shù) -17.5/2 = 0.5 余數(shù) -17.5/0 = -nan
#include <iostream> #include <cmath> using namespace std; int main() { int x = 5; double y = 2.13, result; result = remainder(x, y); cout << "余數(shù) " << x << "/" << y << " = " << result << endl; return 0; }
運(yùn)行該程序時(shí),輸出為:
余數(shù) 5/2.13 = 0.74