简体   繁体   English

精确数字后的“随机”数字

[英]'random' numbers after exact numbers

I'm trying to make IF condition where I'm trying to print some text when number is 'correct'.我正在尝试创建 IF 条件,当数字为“正确”时,我尝试打印一些文本。 The question is what if the condition can't have 'exact number' ?问题是如果条件不能有“确切数字”怎么办? Like when you are finding everything (*) in linux system "find / -name *.mp3".就像当您在 linux 系统“find / -name *.mp3”中查找所有内容 (*) 时一样。

Here is my code, sure it do not work work for bad syntax but I put it here for example about my question:这是我的代码,确保它不适用于糟糕的语法,但我把它放在这里,例如关于我的问题:

#include <iostream>

int main() {
        double b = 6.922083e-07;
        if (b == 6.922.*e-07) {
                printf("LOL \n");
        }
}

.* by this I mean everything other which do not matter. .* 我的意思是其他无关紧要的一切。

Thank you very much, will be happy as an elephant if you can help me.非常感谢,如果你能帮助我,我会像大象一样快乐。 I'm stupid and I just can't find it on google.我很笨,我在谷歌上找不到它。

You can write a function to automate the task of getting the exponent:您可以编写一个函数来自动执行获取指数的任务:

int get_expo(double num){
  int n = 0;
  double number = num;
  if(number > 1 && number !=0){
      while (number > 1){
          number/=10;
          n++;
      }
      n-=1;
   }else{
       while(number < 1){
            number*=10;
            n++;
       }
       n = -n;
  }
  return n;
}

And then you can multiply that number by the 10^ exponent plus 3 if you want three digit precision and then convert it to int :然后,如果您想要三位数精度,则可以将该数字乘以 10^ exponent加 3,然后将其转换为int

#include <math.h>
int converted_num = d*pow(10 , get_expo(d) + 3);
if(converted_num == 6922)
{
   //Do something
}

Note that I used 6922 instead of 6.922请注意,我使用的是6922而不是6.922

If you want "close enough" to be 1e-8, for example:如果您希望“足够接近”为 1e-8,例如:

double eps = 1.0e-8;
if (b > (6.922083e-07 - eps) && b < (6.922083e-07 + eps)) {
    printf("LOL \n");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM