30.3k views
2 votes
write a method, printhoursmins, that takes a number of hours as a double and that prints the corresponding whole numbers of hours and minutes. for instance, the call printhours mins(1.25) should print 1 h 15 min since there is 1 hour and 15 minutes in 1.25 h (0.25 * 60

1 Answer

2 votes

Answer:

in java:

public static void printhoursmins(double hours) {

int h = (int) hours;

int m = (int) ((hours - h) * 60);

System.out.println(h + " h " + m + " min");

}

in python:

def printhoursmins(hours):

hours = int(hours)

minutes = int((hours - int(hours)) * 60)

print(f"{hours} h {minutes} min")

in C++:

#include <iostream>

#include <cmath>

void printhoursmins(double hours) {

int h = (int) hours;

int m = (int) round((hours - h) * 60);

std::cout << h << " h " << m << " min" << std::endl;

}

Step-by-step explanation:

  1. Python, the method printhoursmins takes in a double value hours and converts it to an integer value for the number of hours by using the int function. The number of minutes is calculated by subtracting the integer value of hours from the original value of hours, and then multiplying the result by 60. This intermediate result is then converted to an integer value for the number of minutes using the int function. Finally, the number of hours and minutes are printed using string formatting with the print function and the f stringsyntax (f"{hours} h {minutes} min").
  2. In Java, the method printhoursmins is a static method that takes in a double value hours and converts it to an integer value for the number of hours using a typecast to int. The number of minutes is calculated in a similar manner to Python, by subtracting the integer value of hours from the original value of hours and then multiplying the result by 60. This intermediate result is then converted to an integer value for the number of minutes using another typecast to int. Finally, the number of hours and minutes are printed using string concatenation with the println method from the System.out object.
  3. In C++, the method printhoursmins takes in a double value hours and converts it to an integer value for the number of hours using a typecast to int. The number of minutes is calculated in a similar manner to Python and Java, by subtracting the integer value of hours from the original value of hours and then multiplying the result by 60. This intermediate result is then rounded to the nearest integer using the round function from the cmath library, and then converted to an integer value for the number of minutes using another typecast to int. Finally, the number of hours and minutes are printed using the << operator and the endl manipulator from the std::cout object.
User Rasputin Jones
by
7.8k points