003-006-010
Type Casting: Understanding Precision Conversion
Medium
Problem Description
Type Casting: Understanding Precision Conversion
In this problem, you will create a program that reads a double price and tax rate from standard input, multiplies them, casts the result to int (truncating the decimal part), and displays the tax amount to standard output.
Learning Objective: Understand precision loss when casting from double to int and correctly predict calculation results
Overview
In Java, cast operators are used when converting between different numeric types. When converting from floating-point numbers (double) to integers (int), the decimal part is truncated.
Input Format
price (double)
taxRate (double)
Specifications
Implement the following:
- Read a double
pricefrom standard input - Read a double
taxRatefrom standard input - Calculate
price * taxRate - Cast the result to int and store in variable
taxAmount - Output the int-casted
taxAmount
Output Format
(tax amount cast to int)
Sample I/O
Input:
1999.99
0.1
Output:
199
Hint
- The cast operator
(int)truncates the decimal part - 1999.99 * 0.1 = 199.999, but when cast to int, it becomes 199
- Use
nextDouble()to read a double value fromScanner
Ready to Try Running Code?
Log in to access the code editor and execute your solutions for this problem.
Don't have an account?
Sign Up