gpt4 book ai didi

c - 在 C 中修剪 -PI 和 +PI 之间的数字的最快方法是什么?

转载 作者:行者123 更新时间:2023-12-01 15:59:03 25 4
gpt4 key购买 nike

假设我有一个高 float ... 1345.23我想将它减少 2*PI 直到它保持在 -PI 和 +PI 之间,所以我会这样做:

#define PI  3.14159265358f
#define TWO_PI 6.28318530718f

float a = 1345.23f;
while (a > PI) a -= TWO_PI;

你知道最快的方法吗?

最佳答案

使用此代码,您将仅进入循环 1 次(您可以将其延迟添加更多 a -= TWO_PI

#include <stdio.h>

#define PI 3.14159265358f
#define TWO_PI 6.28318530718f

int main(void) {

float a = 1345.23f;
float b = 1345.23 - PI;
int c = b/TWO_PI;

a -= c*TWO_PI;
int i = 0;
while (a > PI){
a -= TWO_PI;
printf("%d",i++);
}

printf("\na : %f",a);
}

输出:

0
a : 0.628314

虽然您的代码将执行 cicle 操作:

214 times

更好的代码:

#include <stdio.h>

#define PI 3.14159265358f
#define TWO_PI 6.28318530718f
#define INV_TWO_PI 0.15915494309189533

int main(void) {

double a = 1345.23;
if(a > PI){

double b = a - PI; // you get the distance between a and PI

// int c = b/TWO_PI; // you get the integer part
int c = b * INV_TWO_PI; // the same as above using multiplication

a -= (c+1)*TWO_PI; // you just subtract c+1 times TWO_PI
// c+1 cause you want come in the range [-PI,PI]
}
}

关于c - 在 C 中修剪 -PI 和 +PI 之间的数字的最快方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37470999/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com