1

以下代码在 CodeBlocks 编译器上运行良好,但在 MPLAB C18 编译器上我没有得到相同的结果。我正在使用 PIC18 微控制器。

代码

    int d[6];
    int all;

    d[0] = 6;
    d[1] = 4;
    d[2] = 8;
    d[3] = 0;
    d[4] = 0;

    all =  10000*d[0] + 1000*d[1] + 100*d[2] + 10*d[3] +  d[4];
    printf("%d", all);

代码块上的输出:64800

MPLAB 上的输出:-816

究竟是什么问题?这段代码不应该正常工作吗?谢谢!

4

2 回答 2

2

Objects that have the type int aren't guaranteed to be able to store values beyond -32767 or 32767. Your Code::Blocks implementation happens to extend this range, but your MPLAB C18 implementation (which isn't really a valid C implementation, by the way) doesn't. What you're seeing in your MPLAB implementation is undefined behaviour due to signed integer overflow. Use an unsigned type, and/or a wider type, such as long or long long. Don't forget to modify your printf format specifier accordingly. %u for unsigned int, %ld for long, %lu for unsigned long, %lld for long long, etc...

于 2013-05-06T16:35:44.117 回答
0

according to this link , Your MCU is 8-bits system. so the length of the integer of your system is 16 bits. when you simulate your code with CodeBlocks, you are running your code with a 32-bits system ( or 64-bits system ) and the size of integer is 32 bits. so you will not get the same results. because in your MPLAP system you are overflowing the integer size

于 2013-05-06T16:34:44.767 回答