首页 > 解决方案 > Multiplication is returning me incorrect values

问题描述

I am writing some code for an Arduino project I am working on, and the multiplication is returning me incorrect values, and I can't figure out why.

String calculateShutterSpeed(float fs, int i, int l){
float fstop = fs;
int iso = i;
int lux = l;
float c = 1.00;
float shutterspeedTop = 0;
double shutterspeedBottom = 0;

shutterspeedTop = pow(fs, 2)*c;
shutterspeedBottom = lux*iso;

shutterspeedBottom = shutterspeedBottom/shutterspeedTop;

The code giving me the error is the line where I multiply lux by iso, in some cases (with small numbers) it works fine, but as soon as I use larger numbers it starts giving me incorrect numbers, such as a lux of 4833 and iso of 200 will give me a result of -16440.

标签: c++arduino

解决方案


根据您拥有的板,int 的大小将是两个或四个字节。

将两个 2 字节整数相乘会产生另一个 2 字节整数,如果范围太大,则会溢出;这是您看到的行为。

你必须去一个long,或者,也可以,一个double


推荐阅读