在 Arduino 中将变量从一种类型转换为另一种类型


要将变量从一种类型转换为另一种类型,请使用 CAST 运算符。语法为 -

(type) var;

其中var是要转换的变量,type 是你希望转换到的新类型。例如,如果你有一个类型为 float 的变量,并希望将其转换为 int。

示例

方法如下 -

float f;
int i;

void setup() {
   // put your setup code here, to run once:
   f = 5.6;
   i = (int) f;
   Serial.println(f);
   Serial.println(i);
}

void loop() {
   // put your main code here, to run repeatedly:
}

Serial Monitor 将打印 5.6,然后打印 5(而不是 6)。这是因为将float转换为 int 会截断float,而不是四舍五入。

更新于: 31-Jul-2021

3K+ 浏览次数

开启您的 职业 生涯

通过完成课程获得认证

开始
广告
© . All rights reserved.