gpt4 book ai didi

c - for 循环中 pow 函数的值错误

转载 作者:行者123 更新时间:2023-11-30 15:26:54 24 4
gpt4 key购买 nike

我正在尝试在 Arduino 上制作一个 IP 计算器,但在这部分我得到了错误的结果,我期待 128,但它返回 127,我认为问题出在 pow 函数(2,i )因为如果我用 (2,7) 对 pow 进行硬编码,我会得到 128。这就是代码

result=0;
binNumber="10110100"; //I this bin number in another function
firstchar= binNumber.substring(0, 1); //extract the first char
c0="0000000";
fullNumber= firstchar + c0;
for(int i=0;i<=7;i++){
x = String (fullNumber[7-i]);
xint= x.toInt();
result= result + xint * pow(2,i);
}
lcd.print(result);

最佳答案

不要使用pow(2,i) 。使用1<<i 。通过使用位移位,您将避免可能的浮点错误。

关于c - for 循环中 pow 函数的值错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27259034/

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