THINK FIRST·CODE LATER

← All labs

The Ariane 5 conversion: detect overflow instead of hiding it

Problem

Ariane 5 was lost because a 64-bit floating-point value was converted to a 16-bit signed integer that could not hold it. In Java, a 16-bit signed integer is a short, with range −32768 … 32767. A plain cast like (short) 40000.0 does not fail — it silently produces a wrong value.

Write a program that reads n and then n real numbers (sensor values). For each value v:

  • if v is between −32768 and 32767 (inclusive), convert it by truncating toward zero (as (short) v would) and print v -> result;
  • otherwise print v -> OVERFLOW (a plain cast would give X), where X is the wrong value that (short) v actually produces.

Print v exactly as Java prints a double. At the end print Safe: a, Overflow: b.

For the input

4
123.9
40000
-32768
-40000.5

the output must be:

123.9 -> 123
40000.0 -> OVERFLOW (a plain cast would give -25536)
-32768.0 -> -32768
-40000.5 -> OVERFLOW (a plain cast would give 25536)
Safe: 2, Overflow: 2

Write it here or in your IDE, then paste it. Compile and test it yourself before comparing. Your code stays in your browser — it is never sent to or stored on the server.