This thread has been locked.

If you have a related question, please click the "Ask a related question" button in the top right corner. The newly created question will be automatically linked to this question.

[参考译文] TMS320F280041:整数乘法和除法计算错误

Guru**** 2538950 points


请注意,本文内容源自机器翻译,可能存在语法或其它翻译错误,仅供参考。如需获取准确内容,请参阅链接中的英语原文或自行翻译。

https://e2e.ti.com/support/microcontrollers/c2000-microcontrollers-group/c2000/f/c2000-microcontrollers-forum/1018419/tms320f280041-wrong-calculation-for-integer-multiply-and-divide

器件型号:TMS320F280041

大家好、我还有一个关于整数乘法和除法误差的问题。

CCS 运行时支持库 select:automatic,它显示:F021_API_F28004X_FPU32.lib

我的测试场景如下:

unsigned int a、b、c、d;

A=770;

b =99;

C=47;

d = a * b * c/1000;

正确的值应该是358、但我得到它是4。

  • 请注意,本文内容源自机器翻译,可能存在语法或其它翻译错误,仅供参考。如需获取准确内容,请参阅链接中的英语原文或自行翻译。

    遗憾的是、这不是无符号数学在 C 代码中的工作方式。

    回想一下、在 C28x 上、unsigned int 类型为16位宽、unsigned long 类型为32位宽。  

    当看到像 A*b 这样的表达式时,将选择执行数学运算的类型。  大致说来、使用的是 A 或 b 类型中较大的值。  在本例中、它们都是无符号整型、因此使用的是无符号整型。  如果计算结果不能放入 unsigned int、则结果的高位将被丢弃、其余位将用作结果。  实际上、计算结果是(a * b)& 0xFFFF。   

    解决方案是将至少一个乘法操作数转换为无符号长整型。  虽然只需要一个转换,但要清楚代码的作用,最好转换全部3个操作数...

    d = (unsigned long)a*(unsigned long)b*(unsigned long)c/1000;

    谢谢、此致、

    乔治

  • 请注意,本文内容源自机器翻译,可能存在语法或其它翻译错误,仅供参考。如需获取准确内容,请参阅链接中的英语原文或自行翻译。

    尊敬的乔治:

    谢谢、  

    此致、

    广军