C++ 两个浮点或双精度数的余数
在本教程中,我们将学习如何确定两个浮点数的余数。
示例:
Input: a = 9.7, b = 2.3
Output: 0.5
Input: a = 36.5, b = 5.0
Output: 1.5
C程序:
#include
#include
int main()
{
int x = 10;
int y = 3;
float p = 10.23f;
float q = 3.1f;
double a = 123456789.10;
double b = 1233.1;
printf("remainder(%lf,%lf) = %lf\n", a, b, remainder(a, b));
printf("remainder(%d,%d) = %lf\n", x, y, remainder(x, y));
printf("remainder(%f,%f) = %lf\n", p, q, remainder(p, q));
return 0;
}
输出:
remainder(123456789.100000,1233.100000) = 50.200000
remainder(10,3) = 1.000000
remainder(10.230000,3.100000) = 0.930000
C++ 程序:
#include
using namespace std;
double findingMod(double x, double y)
{
double mod;
if (x < 0)
mod = -x;
else
mod = x;
if (y < 0)
y = -y;
while (mod >= y)
mod = mod - y;
if (x < 0)
return -mod;
return mod;
}
int main()
{
double x = 9.7, y = 2.3;
cout << findingMod(x, y);
return 0;
}
输出结果:
0.5
将两个浮点数的模数找出来,我们可以利用内建的 fmod 函数。
C++ 程序:
#include
using namespace std;
int main()
{
double x = 9.7, y = 2.3;
cout << fmod(x, y);
return 0;
}
输出:
0.5