在 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,而不是四捨五入。
廣告