2.4 Code Practice: Question 2

Write a program that accepts a number as input, and prints just the decimal portion. Your program should also work if a negative number is inputted by the user.

Enter a number: 15.789
Sample Output
0.789

Can someone please help me with this because I’m so stuck

Respuesta :

The code is in Java.

It calculates the decimal portion of a number by subtracting the integer portion from the number. It also uses if structure to check if the number is a negative one.

Comments are used to explain each line of code.

//Main.java

import java.util.Scanner;

public class Main

{

public static void main(String[] args) {

 //Initialize the Scanner object to be able to get input

 Scanner input = new Scanner(System.in);

 

 //Declare the variables

 double number, decimalPortion;

 

 //Ask the user to enter a number

 System.out.print("Enter a number: ");

 number = input.nextDouble();

 

 //Get the decimal portion of the number by subtracting the integer part from the number

 decimalPortion = number - (int) number;

 

 //If the number is negative one, multiply the decimal portion with -1 to convert it to a positive value

 if(number < 0)

     decimalPortion *= -1;

 

 //Print the decimal portion

 System.out.println(decimalPortion);

 

}

}

You may see a similar question in the following link:

brainly.com/question/17132559