Arduino Pow()和阿姆斯特朗数问题

时间:2019-12-19 03:23:01

标签: c++ arduino arduino-uno

这是我要运行的代码。我尝试了很多事情,例如我发现用math.h做一个ceil()的解决方案,但我真的很想了解为什么即使我做类似的事情

,这也行不通

pow((int)j, 3) + pow((int)d, 3) + pow((int)s, 3)

其中j为3,d为5,s为1; 如果我在哪里可以做

pow(3,3) + pow(5,3) + pow(1, 3) 该条件将为真。

我知道sum的类型为double,Serial.println(sum)表示153.00,我想152.999999像这样,但是int j = 3;与普通素3到pow()有何不同我检查了二进制数据,实际上j是0011,d是0101,而s是0001Serial.println(j, BIN);

int n = 100;
float j, d, s;
double sum;
void setup() {
  Serial.begin(9600);
}

void loop() {
  delay(100);
  if (n >= 100 && n < 154) {
    j = n % 10; // 153 % 10 = 3;
    d = n / 10 % 10; // 15 % 10 = 5;
    s = n / 100; // 153 / 100 = 1;

    sum = pow(j, 3) + pow (d, 3) + pow(s, 3);

    if (sum == n) {
      Serial.println(n);
    }

    n++;
  }
}

如果我在这里发现一些错别字,我会纠正自己,我只是在这里输入了它,而不是复制粘贴它:)

2 个答案:

答案 0 :(得分:0)

  

int j = 3;与仅将3放入pow()

有何不同?

pow(int, int)是与pow(float, float)不同的功能。 pow(float, float) 显然很弱,只能对数学上正确的答案给出 close 。 C / C ++未指定此类功能所需的紧密度。

可以对pow(float, float)答案进行四舍五入,或者简单地针对确切的数学问题,避免使用浮点数学。


请记住,更好的结果实现可能会以时间性能为代价。您经常会得到付款。

答案 1 :(得分:0)

真的,如果您使用pow将某物提高到3的幂,则可能是错误的;)

template<typename T> T sqr(const T x) { return x*x; }
template<typename T> T cube(const T x) { return x*x*x; }

但是,是的,pow返回幂的近似值,因此,如果您使用浮点数(如在这里的j,d和s所示),则应该期望有一些舍入误差,并且相应地处理。

如果您只对这里进行整数计算感兴趣,可以将类型更改为int吗?

int j, d, s;