整数绕行不是很好理解
integer wrap-around not really understood
我有以下一段代码,它被称为,大约每秒 100次
if (elapsed_centiseconds_mod_60000 < 59999) {
++elapsed_centiseconds_mod_60000;
} else {
elapsed_centiseconds_mod_60000 = 0;
}
if (elapsed_centiseconds_mod_60000 % 6000 == 0) {
++elapsed_minutes;
}
变量和常量的类型
volatile uint16_t elapsed_centiseconds_mod_60000;
volatile uint8_t start_minute_mod_10;
const int8_t calibration_second = 5;
那么恰好每秒一次,下面的语句被称为
int16_t get_phase_deviation(uint8_t current_second, uint8_t current_minute_mod_10) {
int32_t deviation=
(int32_t) elapsed_centiseconds_mod_60000 -
((int32_t) current_second + (int32_t)600 - (int32_t)calibration_second) * (int32_t) 100 -
((int32_t) current_minute_mod_10 + (int32_t) 60 - (int32_t)start_minute_mod_10)* (int32_t)6000;
deviation %= 60000;
return (int16_t)(deviation<=30000? deviation: deviation-60000);
}
代码的思想是检测两个振荡器的相对频率误差。然而,代码并没有像预期的那样工作。它将开始输出一个0的偏差。但是,一旦经过的厘秒比它们应该的多一厘秒,它将立即跳转到5537的输出,这与2^ 16% 60000 + 1相吻合。我试图将中间值转换为int32_t,但问题仍然存在。通常在100秒或10000厘秒后出现问题。我怀疑有一些绕圈子的问题,但我看不出来。
有谁知道是哪个词引起的,为什么?
您错误地将get_phase_deviation()
的返回值转换为deviation %= 60000
的范围是-59999 to 59999
(而不是 0 to 59999
)。你应该改变这一行:
return (int16_t)(deviation<=30000? deviation: deviation-60000);
正确处理偏差<= -30000视情况而定,或者将返回类型更改为int32_t
。
查看具体案例来理解你得到的数字,假设:
calibration_second = 0;
start_minute_mod_10 = 0;
那么对于一个完美的系统,get_phase_deviation()
返回:
deviation = -420000; // As computed
deviation %= 60000; // == 0
return 0;
如果您领先1厘秒,则变为:
deviation = -419999; // As computed
deviation %= 60000; // == -59999
return (int16_t) (-59999); // == 5537
相关文章:
- 我编写了代码将十进制分数转换为其二进制等效数.它编译得很好,但在执行时挂起
- 很好的语法来获取对向量/数组数据的大小引用?
- 我认为我的代码很好,但它在 cin a 之后停止并且没有进一步?
- 尽管一切看起来都很好,但值不会交换
- 为什么不同类型层次结构的指针之间的dynamic_cast定义得很好?
- 在 C++11 中利用 int*_t、int_fast*_t 和 int_least*_t 之间的差异的一个很好的例子是
- 对于短字符串来说,这是一个很好的哈希函数吗?
- 为什么指标有时效果很好,有时效果不佳?写下霍夫曼代码
- Red Hat:使用<atomic>编译很好,但链接器找不到__atomic_store_16;什么库?
- 使用移位的无符号数字作为数组的索引号是一种很好的做法
- 是否很好地使用状态模式来维护当前选定的对象?
- C++|以一种很好的方式将树(不一定是二进制的)打印到stdout
- 静态库单独使用很好,但在引用时会抛出错误
- 如果验证容器的大小并在同一条件语句下访问元素,这是很好的做法吗?
- 可变参数函数模板不能很好地使用 std::function 作为参数
- 有没有办法关闭文件? fclose 不能很好地工作
- 引用的静态强制转换强制模板实例化,其中不完整的类型很好
- libc++:为什么流关闭后仍然很好
- C++20 是否为"overflow"的有符号整数很好地定义了左移?
- 整数绕行不是很好理解