C++ - 类型转换错误

标签 c++ types casting type-conversion avr

所以我在 AVR 微 Controller 上实现了这个功能,但当我调用

display(1)

4 位显示屏上显示的值是“1.099”而不是“1.000”。

void display(float n) {
int8_t i, digit_pos=0;
unsigned short digit;
PORTC &= ~((1<<MUX_A2) | (1<<MUX_B2) | (1<<MUX_E2));
ENABLE_DISPLAY;

for (i=3;i>=-3;i--)
{
    digit = n/pow(10,i);
    digit = digit%10;
    if (digit==0&&i>0&&digit_pos==0)
        continue;
    if (digit_pos-i<3)
        if (i==0)
            digit += 10;

    PORTD = SegCode[digit];
    PORTC = ((PORTC & (~(3<<MUX_A2))) | (digit_pos<<MUX_A2)) & ~(1<<MUX_E2);
    PORTC |= (1<<MUX_E2);
    if (digit_pos==3)
        break;
    else
        digit_pos++;
}

PORTD=0x00;
}

应该显示的“n”变量是一个 float ,那么为什么精度从第二个小数点开始丢失

digit = n/pow(10,i);
digit = digit%10;

是不是因为类型转换?是因为某些 8 位 RISC 处理器的限制吗?

最佳答案

这是因为类型转换。

float 不精确,所以当您在 float 中执行 1/.01 和 1/.001 时,您得到的值会略小于 100 和 1000。(我不想追踪您的彻底编码所有这些,但这就是问题所在。)这被四舍五入为 99 和 999,这就是输出中出现 9 的原因。

如果可以的话,使用整数会更好。通过将最后一个预期数字的值加一半来防止向下舍入。

您似乎期望值介于 0.001 和 9999 之间。快速实现将用例:

if (n > 9999) error
else if (n >= 1000) {dec = (int)(n + 0.5); shift = 0;}
else if (n >= 100) {dec = (int)(10*(n + 0.05)); shift = 1;}
and so on

then do stuff with dec

另一个提示,您不需要使用 % 运算符。从右边计算数字并在显示前存储它们。

dec_next = dec / 10;
digit = dec - 10*dec_next;
dec = dec_next;

关于C++ - 类型转换错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18601871/

相关文章:

c++ - 目标文件 "Version References"来自哪里?

c++ - typedef 到模板类型

Java 初学者 : does casting result in lower performance by any mean?

ios - 从 "UITableViewCell"转换为不相关类型 "UIView"总是失败 iOS9

javascript - 如何在 typescript 中导出类型,它将类型标记为未定义

java - 如果没有应用程序类,我收到此错误 android.app.Application 无法转换为 android.app.Activity

c++ - C 风格的字符串作业

c++ - 为什么不允许从 VirtualBase::* 转换为 Derived::*?

c# - 如何在 "possible"类型的对象之间切换?

typescript - 区分联合类型