go - Go 中的 C++ fmod 等价物是什么?
问题描述
fmod 计算除法的余数 返回 numer/denom 的浮点余数(向零舍入):
fmod = 数字 - tquot * denom
其中 tquot 是截断(即,向零舍入)的结果:numer/denom。
解决方案
import "math"
func Mod(x, y float64) float64
Mod 返回 x/y 的浮点余数。结果的大小小于 y,其符号与 x 的符号一致。
例如,
package main
/*
#cgo LDFLAGS: -lm
#include <math.h>
#include <stdio.h>
double fmodC(double x, double y) {
double mod = fmod(x, y);
printf("%f\n", mod);
return mod;
}
*/
import "C"
import (
"fmt"
"math"
)
func fmodGo(x, y float64) float64 {
mod := math.Mod(x, y)
fmt.Printf("%f\n", mod)
return mod
}
func main() {
x, y := 42.0*3.14159, -2.718
fmt.Println(x, y)
modC := C.fmodC(C.double(x), C.double(y))
modGo := fmodGo(x, y)
fmt.Println(float64(modC) == modGo)
// fmod = numer - tquot * denom
numer := x
denom := y
tquot := float64(int64(x / y))
fmod := math.Mod(numer, denom)
fmt.Println(fmod == numer-tquot*denom)
}
输出:
131.94678 -2.718
1.482780
1.482780
true
true
推荐阅读
- ubuntu - 如何在ubuntu服务器上从tor传递shadowsocks
- sql - 如何获取每年的积分名称和最大值?(SQL)
- layout - 将鼠标悬停在 Snap 布局上时 Windows 11 资源管理器崩溃
- error-handling - ABAQUS 错误“***错误:输出请求 TSHR13 不适用于此选项”
- django - 如何获取调用mixin的模型实例?
- reactjs - 使用 Material UI 的超级菜单
- c++ - 构建 Linphone-SDK 时未导出的函数
- java - 来自 if 语句的奇怪 NullPointerException
- html - 导航栏下拉菜单在 Angular 12 bootstrap 5 中不起作用
- c - 将带有单间接运算符的指针作为指向多维数组的参数,如 arr[x][y][z]