首页 > 解决方案 > Go 中的 C++ fmod 等价物是什么?

问题描述

fmod 计算除法的余数 返回 numer/denom 的浮点余数(向零舍入):

fmod = 数字 - tquot * denom

其中 tquot 是截断(即,向零舍入)的结果:numer/denom。

http://www.cplusplus.com/reference/cmath/fmod/

标签: go

解决方案


包数学

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

推荐阅读