มีหลายวิธีในการตรวจสอบว่าตัวเลขลอยอยู่ใน C++ หรือไม่ ต่อไปนี้เป็นสองวิธีที่พบบ่อยที่สุด:

  1. ใช้ฟังก์ชัน is_float() จากไลบรารี std ฟังก์ชันนี้รับตัวแปรเป็นอาร์กิวเมนต์ และส่งคืนค่า true หากตัวแปรเป็นประเภท float และ false มิฉะนั้น

C++

#include <iostream>
#include <stdexcept>
using namespace std;
int main() {
  float number = 1.23;
  if (is_float(number)) {
    cout << "The number is a float.";
  } else {
    cout << "The number is not a float.";
  }
  return 0;
}
  • ใช้ตัวดำเนินการ typeid() โอเปอเรเตอร์นี้ส่งคืนประเภทของตัวแปร จากนั้นคุณสามารถเปรียบเทียบผลลัพธ์กับ typeid(float) เพื่อตรวจสอบว่าตัวแปรนั้นเป็นประเภท float หรือไม่

C++

#include <iostream>
using namespace std;
int main() {
  float number = 1.23;
  if (typeid(number) == typeid(float)) {
    cout << "The number is a float.";
  } else {
    cout << "The number is not a float.";
  }
  return 0;
}

วิธีที่คุณใช้ขึ้นอยู่กับความชอบของคุณ ฟังก์ชัน is_float() a มีความกระชับมากกว่า แต่ตัวดำเนินการ typeid() นั้นมีความยืดหยุ่นมากกว่า

นี่คือตัวอย่างวิธีใช้ฟังก์ชัน is_float() ใน Python:

หลาม

def is_float(number):
  """
  Returns True if number is a float, False otherwise.
  """
  return isinstance(number, float)

def main():
  number = 1.23
  print(is_float(number))

if __name__ == "__main__":
  main()

รหัสนี้จะพิมพ์ True เนื่องจากตัวแปร number เป็นแบบทศนิยม