Data types and conversions · Coding Class
This topic is not available in the selected language or version. Showing the start of this section.
Apply the chapter in three steps: an exercise, a program project, and a debugging task. Implement first, then consult the hints and completion criteria. Use a separate file or working directory for each task.
1. Exercise · Compare division results
Section titled “1. Exercise · Compare division results”Print 5 / 2, float(5 / 2), and float(5) / 2.0 in order and explain the difference.
Completion: Output is 2, 2.0, and 2.5.
Hint: Find the point where the fractional part is discarded.
2. Build a program · Calculate an average
Section titled “2. Build a program · Calculate an average”Print the floating-point average of scores 7, 8, and 10. Store an integer total, then convert before division. Also check scores 0, 0, and 0.
Completion: The averages are approximately 8.333333 and 0.0. Do not first truncate the result to integer 8.
Hint: Use float(total) / 3.0.
3. Debug · Fix a numeric mismatch
Section titled “3. Debug · Fix a numeric mismatch”Fix the program below while keeping count typed as I32. Explain whether the same fix always works for values outside the I32 range.
Start with this deliberately broken program.
fn main() { let wide: Int = 42; let count: I32 = wide; println(count);}xen check class_numeric.xenDiagnostic excerpt:
expected I32, found Int (I64)Completion: It prints 42 with an explicit conversion; explain that out-of-range conversions fail.
Hint: Use i32(...); narrowing is not implicit.
Verify and record
Section titled “Verify and record”Use xen check file.xen followed by xen run file.xen for ordinary programs; use xen test file.xen for test-only files. Record the original error, its cause, and the corrected result, then rerun every input in the completion criteria.