简体   繁体   中英

Strange computation on an Arduino Mega

Look at this very basic Arduino program:

long pos = 90 * 1023/360;
Serial.println(pos);

It should display 255, but it displays 73. I do not understand why.

This program is run on an Arduino Mega.

Since all of the things on the right side of the equal sign are int sized, the math gets done in an int sized box. The first step is to multiply 90 * 1023 and that result overflows the int. You have to tell the compiler to use long on the right hand side by forcing it to make one of those numbers a long:

long pos = 90L * 1023/360;

您可以简单地将右侧的数字之一变成一个长数字。

long pos = 90 * 1023L/360;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM