不能在双打上使用模数?

Bha*_*axy 176 c++ modulo

我有一个C++程序(使用g ++编译).我正在尝试将两个双精度数作为操作数应用于模数函数,但是我得到以下错误:

错误:类型'double'和'double'到二进制'operator%'的操作数无效

这是代码:

int main() {
    double x = 6.3;
    double y = 2;
    double z = x % y;
}
Run Code Online (Sandbox Code Playgroud)

Mys*_*ial 262

%运营商是整数.你正在寻找这个fmod()功能.

#include <cmath>

int main()
{
    double x = 6.3;
    double y = 2.0;
    double z = std::fmod(x,y);

}
Run Code Online (Sandbox Code Playgroud)

  • @Paul:那可能不是一个bug.如果`angle`是,例如,`359.9999999`,那么`angle`和`fmod(angle,360)`都可能显示为`360`.(根据需要添加更多9个.)尝试使用50位精度打印值. (7认同)
  • 这不适用于负数。`std::fmod(-1.0, 2 * M_PI)` 返回 `-1.0`,我预计大约为 `5.28`。 (2认同)

MSN*_*MSN 36

fmod(x, y) 是你使用的功能.


Mys*_*cal 8

您可以实现自己的模函数来为您做到这一点:

double dmod(double x, double y) {
    return x - (int)(x/y) * y;
}
Run Code Online (Sandbox Code Playgroud)

然后您可以简单地使用dmod(6.3, 2)来获取余数,0.3

  • @tarpista:这是预期的,带有浮点数。 (2认同)

Sce*_*ule 5

使用fmod()<cmath>.如果您不想包含C头文件:

template<typename T, typename U>
constexpr double dmod (T x, U mod)
{
    return !mod ? x : x - mod * static_cast<long long>(x / mod);
}

//Usage:
double z = dmod<double, unsigned int>(14.3, 4);
double z = dmod<long, float>(14, 4.6);
//This also works:
double z = dmod(14.7, 0.3);
double z = dmod(14.7, 0);
double z = dmod(0, 0.3f);
double z = dmod(myFirstVariable, someOtherVariable);
Run Code Online (Sandbox Code Playgroud)

  • 为什么不想包含C头文件?那就是它的目的。 (3认同)