Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

Numeric Types ใน Python: int, float, complex


Python มี numeric types 3 แบบ: integers, floating point, complex (มี real และ imag parts เขียนเป็น a + bj)

ฟังก์ชันแปลงชนิด: int(), float(), complex() ยังมี Fraction และ Decimal สำหรับความแม่นยำ

ออปอเรชันและฟังก์ชันตัวเลข

ออปอเรชัน/ฟังก์ชันคำอธิบาย
x + yบวก
x - yลบ
x * yคูณ
x / yหาร
x // yหารปัดเศษ (floor division)
x % yเศษ
x ** yยกกำลัง
-xค่าตรงข้าม
+xค่าเดิม
abs(x)ค่าสัมบูรณ์
int(x)แปลงเป็น integer
float(x)แปลงเป็น float
complex(re, im)สร้าง complex number
x.conjugate()คอนจูเกตของ complex
divmod(x, y)คืน (quotient, remainder)
pow(x, y)x ยกกำลัง y

ตัวอย่างโค้ด

from fractions import Fraction
x = 100
y = 3.256
print(x + y)
print(x - y)
print(x * y)
print(x / y)
print(x // y)
print(x % 7)
print(12 ** 3)

myComplex1 = complex('7+5j')
myComplex2 = complex('26+8j')
res = myComplex1 + myComplex2
print(res)
print(res.conjugate())
print(divmod(x, 3))
print(Fraction(0.125))

ผลลัพธ์

103.256
96.744
325.59999999999997
30.712530712530715
30.0
2
1728
(33+13j)
(33-13j)
(33, 1)
1/8