如果x接近某个值时为Statement [英] If Statement when x is near a value

查看:119
本文介绍了如果x接近某个值时为Statement的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试解决数值方程式:

I am trying to solve the numerical equation:

sin ^ 2(x)tan(x)= 0.499999

sin^2(x)tan(x) = 0.499999

在C.
中使用while循环但是如果我舍入到0.5,我只能得到打印答案的程序。这让我想到,有没有一种写作方式:

Using a while loop in C. However I was only able to get program to print an answer if I rounded to 0.5. This led me to thinking, is there a way of writing:

For(x=0;x<=360;x=x+0.001)
{ y=f(x)
If(y **is near x**(e.g. Within 1 percent) )
Do something etc.
}

如果值足够接近,有没有办法告诉计算机执行任务。比如在这个if语句中?
谢谢。

Is there a way of telling the computer to execute a task if the value is sufficiently near. Such as in this if statement? Thank you.

推荐答案

使用相对差异,例如:

#include <math.h>

static inline double reldiff(double x, double y)
{
    return fabs(x - y) / fmax(fabs(x), fabs(y));
}

现在您的测试成为:

if (reldiff(x, y) < 0.01)   // 1% as requested

这篇关于如果x接近某个值时为Statement的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆