Files
ViperC/Test/App/float_test.vp
T

85 lines
3.1 KiB
Plaintext
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import stdio
import t, c
# ============================================================
# 联合体(t.CUnion)含浮点字段
# ============================================================
class DataUnion(t.CUnion):
i: int
f: t.CFloat
l: int64
# ============================================================
# 主函数
# ============================================================
def float_test() -> int:
# ============================================================
# 测试 1: 基本浮点变量(float / double)
# ============================================================
f: t.CFloat = 3.14
stdio.printf("float: f=%f\n", f)
d: t.CDouble = 3.141592653589793
stdio.printf("double: d=%lf\n", d)
# 重新赋值
f = 2.5
stdio.printf("float: f=%f\n", f)
# ============================================================
# 测试 2: 联合体浮点字段
# ============================================================
u: DataUnion
u.f = 3.14
stdio.printf("union: u.f=%f\n", u.f)
# 写入 i 字段后,f 的值已被覆盖
u.i = 42
stdio.printf("union: u.i=%d (after f overwritten)\n", u.i)
# ============================================================
# 测试 3: 联合体共享内存验证(float 与 int 共享)
# ============================================================
u2: DataUnion
u2.i = 0
u2.f = 1.0
# 写入 f 后,i 的值应不再是 0
if u2.i != 0:
stdio.printf("union: float overwrites int verified\n")
# ============================================================
# 测试 4: 浮点算术运算(fadd/fsub/fmul/fdiv/frem)
# ============================================================
a: t.CFloat = 1.5
b: t.CFloat = 2.5
stdio.printf("arith: %.2f + %.2f = %.2f\n", a, b, a + b)
stdio.printf("arith: %.2f - %.2f = %.2f\n", a, b, a - b)
stdio.printf("arith: %.2f * %.2f = %.2f\n", a, b, a * b)
stdio.printf("arith: %.2f / %.2f = %.2f\n", a, b, a / b)
# ============================================================
# 测试 5: double 算术运算
# ============================================================
x: t.CDouble = 10.0
y: t.CDouble = 3.0
stdio.printf("arith: %.4lf + %.4lf = %.4lf\n", x, y, x + y)
stdio.printf("arith: %.4lf - %.4lf = %.4lf\n", x, y, x - y)
stdio.printf("arith: %.4lf * %.4lf = %.4lf\n", x, y, x * y)
stdio.printf("arith: %.4lf / %.4lf = %.4lf\n", x, y, x / y)
# ============================================================
# 测试 6: 浮点取模 (frem)
# ============================================================
stdio.printf("arith: 10.0 %% 3.0 = %.4lf\n", x % y)
# ============================================================
# 测试 7: int 与 float 混合运算(int 自动转 float)
# ============================================================
n: int = 3
stdio.printf("arith: %d + %.2f = %.2f\n", n, a, n + a)
return 0